【问题标题】:In Python, how do you do substitutions when the template file contains a "$"?在 Python 中,当模板文件包含“$”时,如何进行替换?
【发布时间】:2019-07-09 17:00:21
【问题描述】:

我正在使用 Python 3.7 和 Django。我想从 Python 中的模板中获取一个字符串,并像这样进行适当的替换......

src = Template(filein.read())
# document data
relative_path = article.path.replace(settings.REDDIT_URL_PREFIX, "")
d = {'relative_path': relative_path, 'comment': comment}
# do the substitution
result = src.substitute(d)

但是,有一个问题。我的模板包含这个

    ["xpath=//a[@onclick='$(this).parent().submit()']", "xpath:attributes"],

美元符号通常用于替换,所以也许是这个原因,我上面的代码因错误而死...

ValueError: Invalid placeholder in string: line 248, col 31

有谁知道我如何修改上面的模板行,以便替换机制忽略该行上的美元符号?

【问题讨论】:

    标签: python django python-3.x templates substitution


    【解决方案1】:

    三个选项:

    1) 遵循转义规则 https://www.simplifiedpython.net/python-template-class/

    • “$$”是一种转义;它被替换为单个“$”。
    • “$identifier” 命名与映射键匹配的替换占位符 的“标识符”。默认情况下,“标识符”必须拼写为 Python 标识符。 “$”之后的第一个非标识符字符 字符终止此占位符规范。
    • “${identifier}”等价于“$identifier”。时需要 有效的标识符字符跟在占位符后面,但不是一部分 占位符的名称,例如“${noun}ification”。

    2) 遵循我扭曲的解决方法

    在常规的 django 模板中,您可以在 javascript 周围放置 {{ verbatium}} {{end verbatium}},但您使用的是 Python 的新字符串模板。我认为您将不得不以某种方式对字符串进行消毒,然后在替换后将其反转。您必须首先将文件作为字符串加载,然后转换为模板

    with open("/path/to/myfile.txt", "rb") as myfile:
       initial = "/n".join(myfile.readlines()[1:])
    initial.replace('$(this)',"QXQQQXQ")
    src = Template(initial)
    result = src.substitute(d)
    result.replace("QXQQQXQ", '$(this)')
    

    3) 只需使用常规 django 模板

    Django 模板具有各种结构,可以让您将字典数据转换为功能网页,而不仅仅是简单的值替换

    【讨论】:

    • 您好,我在“src.replace('$(this)', "QXQQQXQ")”这一行收到错误消息“AttributeError: 'Template' object has no attribute 'replace'”。
    猜你喜欢
    • 1970-01-01
    • 2019-01-21
    • 2012-11-06
    • 2014-05-16
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多