如何在django模板中放大括号? [英] How to put braces in django templates?

查看:185
本文介绍了如何在django模板中放大括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要生成由大括号包围的id(例如{1234})。使用django模板语言,大括号也用于启动变量替换,所以我有一些麻烦来获得我想要的。我试过

I need to produce an id surrounded by braces ( for example "{1234}" ). With the django template language, braces are also used to start a variable substitution, so I have some trouble in obtaining what I want. I tried

{{{ id }}}
{{ '{'id'}' }}
{{ '{'+id+'}' }}
{ {{ id }} }

这些方法都不行,除了最后一个,不幸的是产生{1234},而不是我想要的。我目前有两个解决方案:我传递一个已经包含{}(ugly)的id变量,或者我编写一个自定义过滤器,然后写入{{id | add_braces}}(我更喜欢它)。

None of these methods work, except the last one, which unfortunately produces "{ 1234 }", not what I want. I currently have two solutions : either I pass an id variable already containing the {} (ugly) or I write a custom filter and then write {{ id|add_braces }} (I prefer it).

在这样做之前,我更愿意询问是否存在更好的解决方案。

Before going this way, I prefer to ask if a better solution exists.

使用转义的值不工作。即使我添加了{%autoescape off%}%7B {%endautoescape%}我没有得到{,这是奇怪的,但这又是一个问题。

Using escaped values does not work. Even if I add {% autoescape off %}%7B{% endautoescape %} I don't get the {, which is strange, but that's another problem.

谢谢

修改:我写了一个快速过滤器。将其粘贴在这里,以便其他人可以将其用作编写更复杂的模板。从django.template的django导入模板
放入python包application_path / templatetags / formatting.py

Edit: I wrote a quick filter. Pasting it here so someone else can use it as a template for writing a more complex one. To be put into python package application_path/templatetags/formatting.py

from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter
@stringfilter
def add_braces(value):
    return "{"+value+"}"


推荐答案

你的答案可以在这里找到:

I think your answer can be found here:

http://docs.djangoproject.com/en/dev/ref/templates/builtins/#templatetag

总之,您要使用 {%templatetag openbrace%} {%templatetag closebrace%}

编辑:
Django现在还包括了这个功能:

Django now also includes this functionality out of the box:

{% verbatim %} {{ blah blah }} {% endverbatim %}

这篇关于如何在django模板中放大括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆