【问题标题】:How can I escape LaTeX special characters inside django templates?如何在 django 模板中转义 LaTeX 特殊字符?
【发布时间】:2013-04-22 00:20:15
【问题描述】:

我有这个用于生成 LaTeX 文件的 django 模板

\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}

但我的列数非常大,因此它们可以包含任何特殊字符。生成 pdf 文件时出现错误。

如何转义所有列中的所有文本?

【问题讨论】:

    标签: python django pdflatex


    【解决方案1】:

    Alex 的回答包括代码中的建议,如果你想复制粘贴:

    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(str(key)) for key in sorted(conv.keys(), key = lambda item: - len(item))))
        return regex.sub(lambda match: conv[match.group()], text)
    

    更换方法见Easiest way to replace a string using a dictionary of replacements?

    【讨论】:

    • 感谢代码!我认为\textless\textgreater之后也应该有一个空格。我得到了“未定义的控制序列”,因为 &lt;a 变成了 \textlessa
    • 是否有理由使用r'\textless ' 而不是r'\textless{}'
    • 不,如果你认为它更好,我会改变它
    • 请注意,'unicode' 函数在 Python 3 中已被弃用,请改用 'str'
    • 我认为没有必要按键对conv进行排序,因为所有键的长度相同。
    【解决方案2】:

    应该这样做:

    CHARS = {
        '&':  r'\&',
        '%':  r'\%', 
        '$':  r'\$', 
        '#':  r'\#', 
        '_':  r'\letterunderscore{}', 
        '{':  r'\letteropenbrace{}', 
        '}':  r'\letterclosebrace{}',
        '~':  r'\lettertilde{}', 
        '^':  r'\letterhat{}', 
        '\\': r'\letterbackslash{}',
    }
    
    print("".join([CHARS.get(char, char) for char in "&%$#_{}~^\\"]))
    

    创建您自己的模板过滤器来过滤您的变量

    [编辑]:

    这是 ConText 的特殊字符,对于 LaTex,适应:

    \& \% \$ \# \_ \{ \} \textasciitilde{} \^{} \textbackslash{}
    

    【讨论】:

    • 别忘了还包括 r'\textgreater' r'\textless'
    • 或 r'\ensuremath{}'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-01
    • 2023-03-06
    • 2015-11-11
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    相关资源
    最近更新 更多