Question

I'm trying to do something that I imagine must be trivial in mako, but I just can't figure out how I should procede and I'm finding the documentation pretty useless. I'm quite familiar with Python and DTL, but I just don't understand why this code is throwing a syntax error.

Basically, all I want to do is take in a datum object (just a small dictionary) and differently generate a link based on where the request is coming from. I know it would be trivial to do this in straight python and pass it in as context, but I'm really trying to warm up to mako. Any help would be hugely appreciated.

<%def name="courseware_link(datum)">
    % if courseware in ${request.url}:
        <a href=${request.url}[:${request.url}.find("courseware")+len("courseware")+1]+datum["url"]>
    % else:
        <a href=${request.host}+"/courses/"+datum["org"]+"/"+datum["course_ids"]+"/#/courseware/"+datum["url"]
    % endif
</%def>

More specifically the syntax error is this:

(SyntaxError) invalid syntax (<unknown>, line 1) (u'if courseware in ${request.url}:pass') in file '/file' at line: 70 char: 1

and line 70 is the second line % if courseware...

Was it helpful?

Solution

You are mixing ${} with regular python in the if conditional and both a tags. Also, you cannot nest ${} inside ${}. You should probably refactor this code to be either out of the template or into a <% %> block, but something like this should work:

%if "courseware" in request.url:
<a href="${request.url[:request.url.find('courseware')+len('courseware')+1]+datum['url']}">
%else:
    <a href="${request.host + '/courses/' + datum['org'] + '/' + datum['course_ids'] + '/#/courseware/' + datum['url']}">
%endif

Here is a refactored version:

<%def name="courseware_link(datum)">
    <%    
    if "courseware" in request.url:
        url = request.url[:request.url.find("courseware")+len("courseware")+1]
        url += datum["url"]
    else:
        url = request.host + "/courses/" + datum["org"] + "/"
        url += datum["course_ids"] + "/#/courseware/" + datum["url"]
    %>
    <a href="${url}">
</%def>

Furthermore you might want to use a routing package to generate your urls instead of building them manually like this, Django should provide something to automatically construct urls.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top