简体   繁体   English

使用mako模板时遇到问题

[英]Trouble using mako templates

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. 我正在尝试做一些我认为在mako中微不足道的事情,但我只是想不出应该怎么做,而我发现该文档毫无用处。 I'm quite familiar with Python and DTL, but I just don't understand why this code is throwing a syntax error. 我对Python和DTL非常熟悉,但是我只是不明白为什么这段代码会引发语法错误。

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. 我知道在纯Python中执行此操作并将其作为上下文传递将是微不足道的,但是我确实在尝试热身于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... % if courseware...第70行是第二行% if courseware...

You are mixing ${} with regular python in the if conditional and both a tags. 你是混合$ {}定期蟒蛇的条件,如果都和a标签。 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. 此外,您可能想使用路由包来生成您的url,而不是像这样手动构建它们,Django应该提供一些东西来自动构建url。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM