Django和Mustache对模板使用相同的语法

DB *_*sai 24 javascript django django-templates javascript-framework mustache

我尝试在HTML中为mustache.js走私HTML模板,但是django模板引擎删除了应该按原样输出到前端的所有占位符

该模板以这种方式包含在HTML中:

<script type="text/x-mustache-template" data-id="header_user_info">
    <div id="header_user_info">
        <div id="notification">0</div>
        <a href="#">{{username}}</a>
    </div>
</script>
Run Code Online (Sandbox Code Playgroud)

我可以通过运行$(el).html()来获取HTML模板,并使用Mustache.to_html(temp,data)生成html;

我可以将所有模板放入另一个静态文件并从CDN提供服务,但是很难跟踪模板所属的位置,以及至少一个额外的http请求.

sur*_*kal 48

您只需更改标记即可:

Mustache.tags = ['[[', ']]'];
Run Code Online (Sandbox Code Playgroud)

  • 为什么逐字标记更好? (2认同)

Chr*_*att 24

您可以使用{% templatetag %}templatetag打印出通常由Django处理的字符.例如:

{% templatetag openvariable %} variable {% templatetag closevariable %}
Run Code Online (Sandbox Code Playgroud)

您的HTML中的结果如下:

{{ variable }}
Run Code Online (Sandbox Code Playgroud)

有关参数的完整列表,请参阅:https://docs.djangoproject.com/en/dev/ref/templates/builtins/#templatetag

  • 虽然这是有效的,但肯定必须有一个更好的方法,而不是替换`{{`with` {%templatetag openvariable%}`的每个实例. (7认同)

cat*_*cat 22

如果你使用django 1.5和更新的使用:

  {% verbatim %}
    {{if dying}}Still alive.{{/if}}
  {% endverbatim %}
Run Code Online (Sandbox Code Playgroud)

如果你坚持使用django 1.2 on appengine使用verbatim模板命令扩展django语法,就像这样......

from django import template

register = template.Library()

class VerbatimNode(template.Node):

    def __init__(self, text):
        self.text = text

    def render(self, context):
        return self.text

@register.tag
def verbatim(parser, token):
    text = []
    while 1:
        token = parser.tokens.pop(0)
        if token.contents == 'endverbatim':
            break
        if token.token_type == template.TOKEN_VAR:
            text.append('{{')
        elif token.token_type == template.TOKEN_BLOCK:
            text.append('{%')
        text.append(token.contents)
        if token.token_type == template.TOKEN_VAR:
            text.append('}}')
        elif token.token_type == template.TOKEN_BLOCK:
            text.append('%}')
    return VerbatimNode(''.join(text))
Run Code Online (Sandbox Code Playgroud)

在您的文件(python 2.7,HDR)中使用:

from django.template import Context, Template
import django
django.template.add_to_builtins('utilities.verbatim_template_tag')

html = Template(blob).render(Context(kwdict))
Run Code Online (Sandbox Code Playgroud)

在你的文件(python 2.5)中使用:

from google.appengine.ext.webapp import template
template.register_template_library('utilities.verbatim_template_tag')
Run Code Online (Sandbox Code Playgroud)

资料来源:http: //bamboobig.blogspot.co.at/2011/09/notebook-using-jquery-templates-in.html


zol*_*tyh 6

尝试使用django-mustachejs

{% load mustachejs %}
{% mustachejs "main" %}
Run Code Online (Sandbox Code Playgroud)

Django-mustachejs将生成以下内容:

<script>Mustache.TEMPLATES=Mustache.TEMPLATES||{};Mustache.TEMPLATES['main']='<<Your template >>';</script>
Run Code Online (Sandbox Code Playgroud)