如何在django模板中避免乳胶特殊字符 [英] How can i escape latex special characters inside django templates
本文介绍了如何在django模板中避免乳胶特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
\documentclass [11pt] {report}
\begin {document}
\begin {table}
\centering
\begin {tabular} {lcr}
\hline
{%for head in head%}
\textbf {{col}}}
{%if not forloop.last%}
&
{%endif%}
{%endfor%}
\\
\hline
{%表%}中的行
{行%}
{%如果不是forloop.last%}
&
{%endif%}
{%endfor%}
\\
{%endfor%}
\hline
\end {表格}
\caption {Simple Phonebook}
\label {tab:phonebook}
\end {table}
\end {document}
但是我的列数不是很大,所以它们可以包含任何特殊字符。我在生成pdf文件时收到错误。
我如何避开所有列中的所有文本
解决方案
Alex的答案包括代码中的建议,如果要复制粘贴:
import re
def tex_escape(text):
:param文本:纯文本消息
:return:消息转义在LaTeX $ b中正确显示$ b
conv = {
'&':r'\&',
'%':r'\%',
'$ ':r'\ $',
'#':r'\#',
'_':r'\_',
'{':r'\\ \\ {',
'}':r'\}',
'〜':r'\textasciitilde {}',
'^':r'\ ^ { }',
'\\':r'\textbackslash {}',
'<':r'\textless',
'>':r' \textgreater',
}
regex = re.compile('|'.join(re.escape(unicode(key))for key in sorted(conv.keys(),key = lambda item: - len(item))))
return regex.sub(lambda match:conv [match.group()],text)
I have this django template which i use to generate Latex files
\documentclass[11pt]{report}
\begin{document}
\begin{table}
\centering
\begin{tabular}{lcr}
\hline
{% for col in head %}
\textbf{ {{col}} }
{% if not forloop.last %}
&
{% endif %}
{% endfor %}
\\
\hline
{% for row in table %}
{% for cell in row %}
{% if not forloop.last %}
&
{% endif %}
{% endfor %}
\\
{% endfor %}
\hline
\end{tabular}
\caption{Simple Phonebook}
\label{tab:phonebook}
\end{table}
\end{document}
But my no of columns are very large so they can contain any special characters in them. I am getting error while generating pdf file.
How can i escape all the text in all columns
解决方案
Alex's answer including suggestions in code, if you want to copy-paste:
import re
def tex_escape(text):
"""
:param text: a plain text message
:return: the message escaped to appear correctly in LaTeX
"""
conv = {
'&': r'\&',
'%': r'\%',
'$': r'\$',
'#': r'\#',
'_': r'\_',
'{': r'\{',
'}': r'\}',
'~': r'\textasciitilde{}',
'^': r'\^{}',
'\\': r'\textbackslash{}',
'<': r'\textless',
'>': r'\textgreater',
}
regex = re.compile('|'.join(re.escape(unicode(key)) for key in sorted(conv.keys(), key = lambda item: - len(item))))
return regex.sub(lambda match: conv[match.group()], text)
See Easiest way to replace a string using a dictionary of replacements? for replacement approach.
这篇关于如何在django模板中避免乳胶特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文