Django and Mustache use the same syntax for template

点点圈 提交于 2019-12-02 20:25:00

You can use the {% templatetag %} templatetag to print out characters that would normally be processed by Django. For example:

{% templatetag openvariable %} variable {% templatetag closevariable %}

Results in the following in your HTML:

{{ variable }}

For a full list of arguments see: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#templatetag

You can simply change the tags:

Mustache.tags = ['[[', ']]'];

If you use django 1.5 and newer use:

  {% verbatim %}
    {{if dying}}Still alive.{{/if}}
  {% endverbatim %}

If you are stuck with django 1.2 on appengine extend the django syntax with the verbatim template command like this ...

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))

In your file (python 2.7, HDR) use:

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

html = Template(blob).render(Context(kwdict))

In your file (python 2.5) use:

from google.appengine.ext.webapp import template
template.register_template_library('utilities.verbatim_template_tag')

Source: http://bamboobig.blogspot.co.at/2011/09/notebook-using-jquery-templates-in.html

Try to use django-mustachejs

{% load mustachejs %}
{% mustachejs "main" %}

Django-mustachejs will generate the following:

<script>Mustache.TEMPLATES=Mustache.TEMPLATES||{};Mustache.TEMPLATES['main']='<<Your template >>';</script>

I have the same issue, but using

{% templatetag openvariable %} variable {% templatetag closevariable %}

is too verbose for me. I've just added a very simple custom template tag:

@register.simple_tag
def mtag(tagContent):
    return "{{%s}}" % tagContent

So that I can now write:

{% mtag "variable" %}
Bobby

You can use the built-in mustache.js set delimiter tag to change the default tags that mustache uses.

i.e.

{{=<% %>=}}

now you can do this:

<% variable %>
Jacob Rief

I have the same issue, so most of the time my variables are part of a translatable string.

{% trans "The ball is {{ color }}" %}

You can use the trans templatetag even if you don't offer i18n.

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