Avoiding ambiguous mustaches from Jinja2 that includes jQuery templates

六月ゝ 毕业季﹏ 提交于 2019-12-02 17:41:09

You can use the {% raw %}{% endraw %} construct to ease your escaping woes (straight from the Jinja2 docs).

Example:

<script type='text/x-jquery-template'>
    <div>The people are:
        {% raw %}<!-- Everything in here will be left untouched by Jinja2 -->

        {{ each people }} 
          ${$value}
        {{ /each }}

        {% endraw %}
    </div>
</script>

I have found this via google while experimenting with polymer but did not like the proposed solution, so another alternative: Use filters.

In your python code define a filter:

#Filter to create curly braces
@app.template_filter('curly')
def curly(value):
    #Handle value as string  {{'foo'|curly}}
    if(isinstance(value,str)):
        return_value = value
    #Handle value directly. {{foo|curly}}
    else:
        return_value = value._undefined_name
    return "{{" + return_value + "}}"

Then in your template you can use {{'foo'|curly}} or {{foo|curly}}

PS: If you don't use flask I think you can't use the decorator but have to register the filter explicitly instead: environment.filters['curly'] = curly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!