phales15
phales15

Reputation: 465

python list and variable into html template

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?

Upvotes: 4

Views: 13970

Answers (3)

Donat3llo
Donat3llo

Reputation: 1

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!

Upvotes: 0

jcollado
jcollado

Reputation: 40424

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.

Upvotes: 5

I82Much
I82Much

Reputation: 27336

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>

Upvotes: 3

Related Questions