另一种(更灵活)的方法可能是将值转换为类似 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 %}
}
或者甚至在这个阶段完全省略模板。祝你好运!