如何代表;{{";在django模板中?

如何代表;{{";在django模板中?,django,django-templates,tex,bibtex,Django,Django Templates,Tex,Bibtex,我试图在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 %}},

我试图在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模板中转义
{
的正确方法是什么?

查看标记:

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

由于模板系统没有“转义”的概念,要显示模板标记中使用的位之一,必须使用
{%templatetag%}
标记

你所追求的是:

{% templatetag openvariable %}
也许有更好的解决方案,因为这不会增加可读性…

带有模板标签

title     = {% templatetag openvariable %}{% templatetag openbrace %} pubentry.title {% templatetag closevariable %}{% templatetag closebrace %},
另一种(更灵活的)方法可能是在将值发送到模板之前将其转换为类似于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 %}
}

或者在这个阶段完全忽略模板。祝你好运!

谢谢!听起来很有趣-我仍在学习Django/Python(到目前为止已经学习了8个小时),但我将对此进行研究。