【问题标题】:Easy Way to Escape Django Template Variables逃避 Django 模板变量的简单方法
【发布时间】:2011-01-12 04:45:25
【问题描述】:

对于一个新项目,我们正在编写文档关于 Django 模板系统。我们也将 Django 用于文档项目本身,因此 Django 会在示例代码中提取我们所有的示例变量并尝试呈现它们。我们发现解决这个问题的唯一方法是使用{% templatetag %},但这会使我们的代码非常不可读。有没有办法让 Django 忽略特定部分中的所有模板变量?

【问题讨论】:

  • +1 - 好问题。我也想知道答案。

标签: django django-templates


【解决方案1】:

Django 1.5 使用verbatim 模板标签解决了这个问题。它也适用于当前的 Django 版本。

{% verbatim myblock %}
    Avoid template rendering via the {% verbatim %}{% endverbatim %} block.
{% endverbatim myblock %}

【讨论】:

  • 它运行良好。它也适用于 Django 1.11。谢谢。
【解决方案2】:

由于 Django 模板词法分析器的限制(就像是一个笨拙的黑客),这是不可能的。但是,如果您愿意将示例代码放在单独的文件中,则可以使用 ssi 标签:

{% ssi /path/to/my/code/examples/example01.html %}

它不会解析文件,只是逐字包含它。但是,这也有限制,因为您不能在包含路径中使用变量(即,如果您移动模板位置,您必须重写或至少查找并替换您的模板文件),并且您必须将包含在settings.py 中的ALLOWED_INCLUDE_ROOTS 设置中的路径(即/path/to/my/code/examples)。 (见http://docs.djangoproject.com/en/dev/ref/templates/builtins/#ssi。)

【讨论】:

  • 哈,我们最初的解决方案是使用 ajax,或者使用“[”而不是“{”,然后用 javascript 替换它们。如果没有其他人会想出更好的东西,我猜你已经回答了。
  • 我更喜欢你的“'['并与 JS 交换”的想法。
【解决方案3】:

一个可能的解决方案是像往常一样编写模板(使用{{ x }}),但将它们保存为 .txt(或您想要的任何其他扩展名)。编写一个在这些文件上运行的脚本,并通过执行模板标签的相反操作(将 {{ 替换为 {% templatetag openvariable %}etc)自动为您创建 .html。确保更新模板后代码运行。

【讨论】:

    【解决方案4】:

    我通过添加一个“include_raw”模板标签解决了这个问题,该标签的行为类似于内置的“include”标签,但只是不解析或处理传递给它的文件。我在 App Engine 下运行 Django 1.2。

    创建一个标签模块(tags.py):

    from django.template import loader
    from google.appengine.ext.webapp import template
    
    register = template.create_template_register()
    
    @register.simple_tag
    def include_raw(path):
      return loader.find_template(path)[0]
    

    注册:

    from google.appengine.ext.webapp import template
    
    template.register_template_library("tags")
    

    使用它:

    {% include_raw "this-will-be-included-verbatim.html" %}
    

    【讨论】:

      【解决方案5】:

      如果您的来源是 HTML,最简单的解决方案是将“{”和“}”替换为各自的 HTML 实体:

      { 变为 {

      } 变为 }

      例子:

      <code>
      To include some other file, you can use the &#123;% include %&#125; template tag. 
      To include a variable, use &#123;%&#123;% varname &#125;%&#125;%.
      </code>
      

      【讨论】:

        【解决方案6】:

        这是解决 Djano 1.4 问题的一种优雅方法。它是一个 Django 自定义标签。 只需创建一个包含以下代码的模块 verbatim_templatetag.py:

        """
        jQuery templates use constructs like:
        
            {{if condition}} print something{{/if}}
        
        This, of course, completely screws up Django templates,
        because Django thinks {{ and }} mean something.
        
        Wrap {% verbatim %} and {% endverbatim %} around those
        blocks of jQuery templates and this will try its best
        to output the contents with no changes.
        """
        
        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))
        

        然后在你的模板中:{% load verbatim_templatetag %}

        不会解析 {% verbatim %} 和 {% endverbatim %} 之间的所有内容。

        来自https://gist.github.com/ericflo/629508的代码

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-09-19
          • 1970-01-01
          • 1970-01-01
          • 2012-05-09
          • 2021-07-16
          • 2012-04-14
          相关资源
          最近更新 更多