在Python中,当模板文件中包含“$”时,如何进行替换?

In Python, how do you do substitutions when the template file contains a "$"?

我正在使用 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

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

三个选项:

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

  • “$$”是一种逃避;它被替换为单个“$”。
  • “$identifier“命名匹配映射键的替换占位符 的“标识符”。默认情况下,“标识符”必须拼写 Python 标识符。 “$”后第一个 non-identifier 字符 字符终止此占位符规范。
  • “${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 模板具有各种构造,可让您将字典数据转换为功能网页,而不仅仅是简单的值替换