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?

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.

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>

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!

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.