[英]how to encode dynamic django variable from a html template in python coding
[英]python list and variable into html template
將輸出列表和變量很好地輸入HTML模板的最佳方法是什么?
list = ['a', 'b', 'c']
template = '''<html>
<title>Attributes</title>
- a
- b
- c
</html>'''
有更簡單的方法嗎?
你應該看看一些模板引擎。 有一個完整列表在這里 。
在我看來,最受歡迎的是:
例如在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']})
這將打印:
<html>
<title>Attributes</title>
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
</ul>
</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>
HTML不支持空格,意思是:
'\n'.join(x for x in list) #won't work
您將嘗試以下操作。
'<br>'.join(x for x in list)
否則模板就是要走的路!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.