0

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
  • 2
    "which gives a syntax error": Always quote the exact error you've got! Commented Oct 1, 2013 at 9:26

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

7 Comments

Thank you so much. I was so close and yet so far. Thanks for helping this newby!
I'm getting the following error. ValueError: unsupported format character '!' (0x21) at index 2615
It seems to be taking every % as a format variable. How do I tell it to escape only the % I don't want?
@DavidBailey: It does. Just use %% for literal %.
So I did a search and replace to the html file. It ain't pretty but it works. Thanks!
|
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.