让 Django 忽略字符串文字
更新 2:问题根本不是 Django 问题 - Python 在到达 Django 之前肯定会删除字符。解决方法是将字符串定义为原始
inputs['variable'] = r'{\bf this is code} \\'
UPDATE:事实证明,这是一个比我乍一看更深入的问题 - 问题是 python 在字符串文字到达 django 之前就将其替换。如果找到解决方案,我将进行更多调查并更新。
我正在使用 django 来处理 LaTeX 模板来生成报告,并且在 Django 替换部分字符串的方式上遇到了很多问题。
具体来说,我在尝试插入包含乳胶代码的变量时遇到了两个问题。
第一个是它会用 HTML 代码替换 HTML 字符,例如小于号,这对于 LaTeX 解释器来说当然是乱码。我通过将上下文设置为从不自动转义来修复此问题,如下所示:
c = Context(inputs)
c.autoescape = False
但是,我仍然有第二个问题,即 Django 将字符串文字替换为其相应的字符,因此双反斜杠变为 \,而 \b 变为退格键。如何强制 Django 将这些字符保留在适当的位置,这样
inputs['variable'] = '{\bf this is code} \\'
时就不会被破坏?
{{variable}}
当我在 django 模板中引用它
UPDATE 2: The problem isn't a Django problem at all - Python was definitely stripping out the characters before it got to Django. The fix is to define the string as raw
inputs['variable'] = r'{\bf this is code} \\'
UPDATE: It turns out this is a deeper question than I thought at first glance - the issue is that python is replacing the string literals before they ever get to django. I will do more investigating and update this if I find a solution.
I'm using django to work with LaTeX templates for report generation, and am running into a lot of problems with the way Django replaces parts of strings.
Specficially, I've run into two problems where I try to insert a variable containing latex code.
The first was that it would replace HTML characters, such as the less than symbol, with their HTML codes, which are of course gibberish to a LaTeX interpreter. I fixed this by setting the context to never autoescape, like so:
c = Context(inputs)
c.autoescape = False
However, I still have my second issue, which is that Django replaces string literals with their corresponding characers, so a double backslash becomes \, and \b becomes a backspace. How can I force Django to leave these characters in place, so
inputs['variable'] = '{\bf this is code} \\'
won't get mangled when I use
{{variable}}
to reference it in the django template?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如上面的更新中所指出的,这根本不是 Django 的问题 - Python 在字符串到达 Django 之前就已经解释了字符串文字。解决方法是将字符串定义为原始字符串。
As noted in the updates above, it wasn't a problem with Django at all - Python was interpreting the string literals before the string even made it to Django. The fix was to define the string as raw.