HTMLテンプレートに出力リストと変数をうまく組み込むにはどうすればよいですか?pythonリストと変数をhtmlテンプレート
list = ['a', 'b', 'c']
template = '''<html>
<title>Attributes</title>
- a
- b
- c
</html>'''
これは簡単な方法ですか?
HTMLテンプレートに出力リストと変数をうまく組み込むにはどうすればよいですか?pythonリストと変数をhtmlテンプレート
list = ['a', 'b', 'c']
template = '''<html>
<title>Attributes</title>
- a
- b
- c
</html>'''
これは簡単な方法ですか?
テンプレートエンジンがあなたのためにあまりにも重い重量であればHTMLは意味、空白をサポートしていません
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>
おそらく、いくつかのテンプレートエンジンがあります。完全なリストhereがあります。私の意見で
、最も人気があります:
:
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']})
これは、印刷されます:
<html>
<title>Attributes</title>
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
</ul>
</html>
注:これは、ほんの少しの例であり、理想的にテンプレートが別々のビジネスロジックとプレゼンテーションを保つために別のファイルにする必要があります。
のように、あなたが何かをすることができます:
'\n'.join(x for x in list) #won't work
あなたが試してみたいと思います以下。
'<br>'.join(x for x in list)
それ以外の場合はテンプレートを使用してください。
私はテンプレートエンジンが好きで、私のお気に入りはStringTemplateです - 利用可能なPythonバインディングもあります。 http://stringtemplate.appspot.com/ – I82Much
OPにもう少し文脈を与えるために、これはPythonのドキュメントが補間演算子を説明する方法です:[String Formatting Operations](http ://docs.python.org/library/stdtypes.html#string-formatting-operations)。 – Paolo