Handling {null} in Mako?

102 views
Skip to first unread message

Han Chuang

unread,
Mar 19, 2013, 6:04:32 PM3/19/13
to mako-d...@googlegroups.com
Hello,

I'm starting out with Mako, I've been working on a project that makes query to a local sqlite db and passes the results into a mako template to be drawn with javascript (Extjs)

def myView(request):
    response = request.db.execute("select * from myTable);
    results = [dict(name=row[0], id=row[1], start=row[2], end=row[3]) for row in response.fetchall()]
    return dict(results=results)

The results are passed into a template and handled, being passed into a javascript function to draw the results.

% if results
    <h2>RESULTS FOUND</h2>
    % for result in results:
        <script>
        myFunction(${result['name']}, ${result['id']}, ${result['start']}, ${result['end']});
        </script>
    % endfor
% else
    <h2>RESULTS LOST</h2>
% endif

However, the dbs I will be using have unexpected {null} items (in this case, end can be null, as can start.) Passing a none to a javascript method seems to break it and not execute it at all. How can I handle nulls in mako?

One method I've found so far is to create an if else statement for each field that can be null, then doing
% if result['name']:
    <Do the method that has it>
% else
    <Do a separate method that doesn't have it>
% endif

But this results in a lot of duplicated code and seems to be inefficient.

Summary: How can I change a None in mako to a null for javascript?

Thank you in advance!


Benjamin Trofatter

unread,
Mar 19, 2013, 8:51:03 PM3/19/13
to mako-d...@googlegroups.com
You could just write a filter that replaces "None" with "null in the output.

# in myfilters.py
def null_if_None(value):
    if value in (None, "None"):
        return "null"
    return unicode(value)

Then you could use this in your templates like so:

% if results
    <h2>RESULTS FOUND</h2>
    % for result in results:
        <script>
        myFunction(${result['name']}, ${result['id']}, ${result['start'] | null_if_None}, ${result['end'] | null_if_None});

        </script>
    % endfor
% else
    <h2>RESULTS LOST</h2>
% endif

And pass the import=["from myfilters import null_if_None"] as a keyword argument to your template renderer.






--
You received this message because you are subscribed to the Google Groups "Mako Templates for Python" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mako-discuss...@googlegroups.com.
To post to this group, send email to mako-d...@googlegroups.com.
Visit this group at http://groups.google.com/group/mako-discuss?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Reply all
Reply to author
Forward
0 new messages