在jinja2模板中格式化和使用字典

时间:2014-03-29 15:31:22

标签: python jinja2 boilerplate

我试图在这个宏调用中添加词典form_labelform_field,但它并不顺利。

从模板中。只有宏线与问题真正相关。 让我再说一遍。 只有宏线与问题真正相关。

{% block content %}
<div id="edit_profile" class="well-lg">
  <fieldset>
    <form id="form_edit_profile" class="form-horizontal" action="{{ url|safe }}" method="post">
       <input type="hidden" name="_csrf_token" value="{{ csrf_token() }}">
       {{ macros.field(form.username, label=_("Username"), form_label={class:"col-xs-2"}, form_field={'placeholder':_("Enter your")+" "+_("Username"), class:"form-control focused required"}) }}
       ...

和支持它的宏。 (已更新,因为我第一次没有将类作为字符串传递。)

{% macro field(field, label='', form_label={},form_field={}) -%}
        <div class="form-group{% if field.errors %} error{% endif %}">
            {% set text = label or field.label.text %}

            {% if field.flags.required %}
                    {{ field.label(text=text + " *", class='control-label '+form_label['class'])}}
            {% else %}
                    {{ field.label(text=text + " ", class='control-label '+form_label['class']) }}
            {% endif %}
            <div class='col-xs-5'>
            {{ field(label, **form_field) }}
            {% if field.errors %}
                {% for error in field.errors %}
                   <label for="{{ field.id }}" class="error help-inline">{{ error }}</label>
                {% endfor %}
            {% endif %}
            </div>
        </div>
{%- endmacro %}

我想知道我是否错误地引用了变量,或者字典键应该是字符串还是我不考虑的东西。

更新了追溯。

Traceback (most recent call last):
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1535, in __call__
    rv = self.handle_exception(request, response, e)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1529, in __call__
    rv = self.router.dispatch(request, response)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
    return route.handler_adapter(request, response)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1102, in __call__
    return handler.dispatch()
  File "/Users/me/Documents/Aptana Studio 3 Workspace/project/bp_includes/lib/basehandler.py", line 89, in dispatch
    webapp2.RequestHandler.dispatch(self)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 572, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 570, in dispatch
    return method(*args, **kwargs)
  File "/Users/me/Documents/Aptana Studio 3 Workspace/project/bp_includes/handlers.py", line 112, in get
    return self.render_template('login.html', **params)
  File "/Users/me/Documents/Aptana Studio 3 Workspace/project/bp_includes/lib/basehandler.py", line 325, in render_template
    self.response.write(self.jinja2.render_template(filename, **kwargs))
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2_extras/jinja2.py", line 158, in render_template
    return self.environment.get_template(_filename).render(**context)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/jinja2-2.6/jinja2/environment.py", line 894, in render
    return self.environment.handle_exception(exc_info, True)
  File "bp_content/themes/default/templates/login.html", line 1, in top-level template code
    {% extends base_layout %}
TypeError: macro 'field' takes no keyword argument 'placeholder'

2 个答案:

答案 0 :(得分:3)

看起来您正在尝试从没有封闭字符串的字典中引用变量:

  form_label['class']
或许这就是做什么的?此外,

  form_label = {'class': ''}

包含评论

您已将宏定义为&#34;字段&#34;但是其中的变量也是标记的#34;字段。&#34;这可能会使解析器感到困惑。

答案 1 :(得分:1)

在Python中使用字典文字时,这是常见问题。

my_dict = {
  key: value
} 

要求您定义名为keyvalue的变量,实际上

key = 1
value = 0

my_dict = {
 key: value
}

将创建您的字典,与:

相同
my_dict = {
  1 : 0
}

因此,如果您想要输入密钥为'key'的字典,则必须引用它

my_dict = {
 'key': 'value'
}

Jinja2模板也不例外:

 {% macro field(field, label='', form_label={class:""},form_field={class:""}) -%}

这里有两个问题:

  • 这需要定义class

  • 标识符field使用了两次

将其替换为:

{% macro field_macro(field, label='', form_label={'class':""},form_field={'class':""}) -%}

当然:

 {{ field_macro(form.username, label=_("Username"), form_label={'class':"col-xs-2"}, 
        form_field={'placeholder':_("Enter your")+" "+_("Username"), 
            'class':"form-control focused required"}) }}

这里的另一个问题是默认函数参数。

如果使用默认参数(即没有为该参数传递任何内容),您将在宏中更改form_field(您可以在jinja中执行此操作),所有其他没有参数的调用将使用更改的值。