[英]How to I pass arguments in to an html string with python?
I'm sure this is trivial but I can't get my arguments into my HTML string. 我确信这是微不足道的,但我无法将我的参数放入我的HTML字符串中。 I downloaded a standard template from https://templates.campaignmonitor.com/ .
我从https://templates.campaignmonitor.com/下载了一个标准模板。 I've tried:
我试过了:
Extract from 'index.html': 从'index.html'中提取:
< p align="left" class="article-title">< singleline label="Title">%(headline)< /singleline>< /p>
Here is some code working on this as input: 以下是一些代码作为输入:
f = open('index.html','r')
html = str(f.read())
html_complete = html % (headline='Today is the day')
which gives a syntax error. 这给出了语法错误。 (html prints fine).
(html打印很好)。
Also tried {} notation but I get a KeyError probably because there are "{" all over the html. 还尝试了{}符号,但我得到一个KeyError可能是因为html上有“{”。
The format character is mandatory. 格式字符是必需的。 The placeholder sequence is
占位符序列是
%(headline)s ^ the s is required!
()
is just parenthesis. ()
只是括号。 With ,
(which you don't have) they'd construct a tuple, but tuple can't contain assignment anyway. 随着
,
(你没有),他们会建立一个元组,但元组不能包含分配反正。 You want a dictionary, which is constructed with curly braces and colons, not equal signs: 你想要一个用大括号和冒号构造的字典,而不是等号:
html % {'headline': 'Today is the day'}
or with dict
function and named arguments: 或者使用
dict
函数和命名参数:
html % dict(headline='Today is the day')
Using operator %
is OK for a few substitutions, but for large HTML file you should probably use some templating system. 使用operator
%
可以进行一些替换,但对于大型HTML文件,您应该使用一些模板系统。 I'd recommend genshi . 我推荐genshi 。 It's templates are well-formed xml, it guarantees well-formed xml output and it allows having dummy text in the document, so you can view the template directly in browser to check the layout and than give it to the application to fill in actual data.
它的模板是格式良好的xml,它保证了格式良好的xml输出,并允许在文档中包含虚拟文本,因此您可以直接在浏览器中查看模板以检查布局,并将其提供给应用程序以填充实际数据。
In your line 在你的行
html_complete = html % (headline='Today is the day')
try this: 尝试这个:
html_complete = html % dict(headline='Today is the day')
To avoid the syntax error. 避免语法错误。
And fix your HTML template according to what Jan Hudec stated in his answer (add the s
). 并根据Jan Hudec在答案中说明的内容(添加
s
)修复HTML模板。
Note: That dict(a=b)
is the same as { "a": b }
, it just helps avoiding the double quotes. 注意:该
dict(a=b)
与{ "a": b }
,它只是有助于避免使用双引号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.