Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 857
phales15 Avatar asked Feb 21 '23 19:02

phales15


1 Answers

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

In my opinion, the most popular are:

  • django.template
  • jinja2
  • genshi

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.

like image 121
jcollado Avatar answered Mar 07 '23 23:03

jcollado