简体   繁体   中英

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. I downloaded a standard template from https://templates.campaignmonitor.com/ . I've tried:

Extract from '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).

Also tried {} notation but I get a KeyError probably because there are "{" all over the html.

  1. The format character is mandatory. The placeholder sequence is

     %(headline)s ^ the s is required! 
  2. () 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:

     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. I'd recommend 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.

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 ).

Note: That dict(a=b) is the same as { "a": b } , it just helps avoiding the double quotes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM