如何在 Django 模板中表示“{{”?

11

我正在尝试在Django中输出bibtex格式,模板看起来像这样:

@{{ pubentry.type }{,
  author    = {{% for author in pubentry.authors.all %}{{ author.first_name }} {{ author.middle_name }} {{ author.last_name }}{% if not forloop.last %} and {% endif %}
              {% endfor %}},
  title     = {{{ pubentry.title }}},
  journal   = {{{ pubentry.journal }}}
}

问题在于{{{{{%。解决此问题的一种方法是在第一个{后面添加一个空格,但这会破坏格式。在Django模板中转义{的正确方法是什么?

3个回答

12

请查看templatetag标签:

输出用于组成模板标签的语法字符之一。

由于模板系统没有“转义”的概念,因此要显示模板标记中使用的某个位,请使用{% templatetag %}标签。

您需要的是:

{% templatetag openvariable %}

也许有更好的解决方案,因为这不会增加可读性...


3

另一种(更灵活的)方法可能是在将值发送到模板之前将其转换为类似bibtex的值。您可能需要这样做来转义一些bibtex / latex无法处理的字符。以下是我之前准备的类似内容:

import datetime

class BibTeXString(unicode):
  pass

def bibtex_repr(obj):
  """ A version of the string repr method, that always outputs variables suitable for BibTeX. """
  # If this has already been processed, it's ok
  if isinstance(obj, BibTeXString):
    return obj
  # Translate strings
  if isinstance(obj, basestring):
    value = unicode(obj).translate(CHAR_ESCAPES).strip()
    return BibTeXString('{%s}' % value)
  # Dates
  elif isinstance(obj, datetime.date):
    return BibTeXString('{%02d-%02d-%02d}' % (obj.year, obj.month, obj.day))
  # Integers
  if isinstance(obj, (int, long)):
    return BibTeXString(str(obj))
  else:
    return BibTeXString(repr(obj))


CHAR_ESCAPES = {
  ord(u'$'): u'\\$',
  ord(u'&'): u'\\&',
  ord(u'%'): u'\\%',
  ord(u'#'): u'\\#',
  ord(u'_'): u'\\_',
  ord(u'\u2018'): u'`',
  ord(u'\u2019'): u"'", 
  ord(u'\u201c'): u"``", 
  ord(u'\u201d'): u"''" ,
  ord(u'\u2014'): u'---', 
  ord(u'\u2013'): u'--',
}

你甚至可以将此用作模板过滤器,如果你想的话,这样可以让你的模板看起来像这样:

@{{ pubentry.type }{,
  author    = {% filter bibtex %}{% for author in pubentry.authors.all %}{{ author.first_name }} {{ author.middle_name }} {{ author.last_name }}{% if not forloop.last %} and {% endif %}{% endfor %}}{% endfilter %},
  title     = {{ pubentry.title|bibtex }},
  journal   = {{ pubentry.journal|bibtex }}
}

但是在内容到达模板之前,我会对其进行转义,这样你的模板只需要执行以下操作:

@{{ pubentry.type }{,
  {% for field in fields %}{{ field }}{% if not forloop.last %},{% endif %}{% endfor %}
}

甚至可以在这个阶段完全省略模板。祝你好运!


谢谢!听起来很有趣 - 我目前只有8小时的Django/Python学习经验,但我会研究一下这个。 - rxin

1

使用templatetag模板标签。

title     = {% templatetag openvariable %}{% templatetag openbrace %} pubentry.title {% templatetag closevariable %}{% templatetag closebrace %},

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接