Search code examples
pythontemplate-engine

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?


Solution

  • 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>