4

What is the best way to get outputted list and variables nicely into an HTML template?

list = ['a', 'b', 'c']
template = '''<html>
<title>Attributes</title>
- a
- b
- c
</html>'''

Is there an easier way to do this?

jcollado
40.5k9 gold badges108 silver badges139 bronze badges
asked Jan 16, 2012 at 18:19

3 Answers 3

5

You should probably have a look at some template engine. There's a complete list here.

In my opinion, the most popular are:

For example in jinja2:

import jinja2
template= jinja2.Template("""
<html>
<title>Attributes</title>
<ul>
 {% for attr in attrs %}
 <li>{{attr}}</li>
 {% endfor %}
</ul>
</html>""")
print template.render({'attrs': ['a', 'b', 'c']})

This will print:

<html>
<title>Attributes</title>
<ul>
 <li>a</li>
 <li>b</li>
 <li>c</li>
</ul>
</html>

Note: This is just a small example, ideally the template should be in a separate file to keep separate business logic and presentation.

answered Jan 16, 2012 at 18:26
Sign up to request clarification or add additional context in comments.

Comments

3

If a template engine is too heavy weight for you, you could do something like

list = ['a', 'b', 'c']
# Insert newlines between every element, with a * prepended
inserted_list = '\n'.join(['* ' + x for x in list])
template = '''<html>
<title>Attributes</title>
%s
</html>''' %(inserted_list)
>>> print template
<html>
<title>Attributes</title>
* a
* b
* c
</html>
answered Jan 16, 2012 at 18:28

2 Comments

That being said, I do like template engines and my favorite is StringTemplate - there are python bindings available as well. Stringtemplate.org or you can play around with it at stringtemplate.appspot.com
To give OP some more context, this is how Python documentation explains the interpolation operator: String Formatting Operations.
0

HTML doesn't support whitespace, meaning:

'\n'.join(x for x in list) #won't work

You'll want to try the following.

'<br>'.join(x for x in list)

Otherwise templates is the way to go!

Peter O.
33.1k14 gold badges86 silver badges97 bronze badges
answered Aug 26, 2014 at 23:07

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.