[英]Custom templates in python
我正在嘗試在python中實現自定義模板格式以完成兩件事
Django喜歡分隔符
{{占位符}}
例如。
from string import Template
class MyTemplate(Template):
delimiter="{{..}}" #it is only for clarification purpose, though it is invalid
mt = MyTemplate("HELLO {{ world }}")
mt.substitute(world="WORLD")
如果存在鍵錯誤或值錯誤,請跳過該標識符。
class MyTemplate(Template):delimiter =“ {{..}}”“#僅用於說明目的
data =“ HELLO {{world}},這是第一個程序{{program}}”
mt = MyTemplate(數據)
mt.substitute(世界= “WORLD”)
那么o / p應該是
HELLO WORLD, this is 1st program
據我所知,我們可以使用諸如jinja2之類的模板引擎,但這是我的最后選擇。 我更喜歡使用python本地庫來做到這一點。
雖然如果您想建議任何模板引擎(如果可能,並帶有示例),那么它也將是不錯的。
提前致謝。
如果您只想做簡單的字符串格式化,python就會包含str.format()
方法以及Template Strings 。
>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
>>> d = dict(who='tim')
>>> Template('Give $who $100').substitute(d)
Traceback (most recent call last):
...
ValueError: Invalid placeholder in string: line 1, col 11
>>> Template('$who likes $what').substitute(d)
Traceback (most recent call last):
...
KeyError: 'what'
>>> Template('$who likes $what').safe_substitute(d)
'tim likes $what'
如果您需要在模板中引入任何形式的邏輯,那么我會大膽地說,正確地編寫自己將是您的頭上方法,並且您想使用一個庫。 Jinja2是出色的通用模板庫。 如果您曾經使用過Django的模板系統,那將是一件輕而易舉的事,因為Jinja2基於Django。
import jinja2
jinja2.env = jinja2.Environment(
loader=jinja2.PackageLoader(package_name=__name__,
package_path='templates'),
trim_blocks=True,
extensions=[
'jinja2.ext.with_', # add the with tag
],
)
context = {
'results': results,
'javascript': js,
'css': css,
'version': '.'.join(str(n) for n in __version__),
}
template = env.get_template('my_template.html')
rendered_template = template.render(context)
<html>
<head>
<title>Hello World</title>
<style>{{ css }}</style>
<script>{{ javascript }}</script>
</head>
<body>
<h1>Hello world</h1>
<ul>
{% for result in results %}
<div>
{{ result.winner_name }}<br />
{{ result.get_score() }}
</div>
{% endfor %}
</ul>
</body>
</html>
Django模板和Jinja2模板之間的區別是Jinja2的理念不是要使設計人員易於使用。 因此,允許在模板內進行函數調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.