模板引擎 pyTenjin 的一些学习 号称全球最快的模板引擎

官方文档:英文文档
参考链接:http://www.187299.com/archives/1876
官方速度测试

简单做一下学习记录 方便以后用到时候翻阅

如果遇到没有描述清楚的 请移步官方文档

**

检查模板语法

**

您可以通过’pytenjin -z’检查模板语法。

模板文件的语法检查

$ pytenjin -z views/*.pyhtml
views/page.pyhtml - ok.

**

一串简单代码的描述

**

<?py # -*- coding: utf-8 -*- ?>
<?py
from setting import *
from tenjin.helpers.html import *
?>
<?xml version=”1.0″ encoding=”utf-8″?>
<feed xmlns=”http://www.w3.org/2005/Atom”>
<title>#{ SITE_TITLE }</title>
<subtitle>#{SITE_SUB_TITLE}</subtitle>
<link rel=”alternate” type=”text/html” href=”http://#{curdomain}/” />
<link rel=”self” type=”application/atom+xml” href=”http://#{curdomain}/index.xml” />
<id>http://#{curdomain}/</id>
<updated>#{site_updated}</updated>
<rights>Copyright © 2010, #{ SITE_TITLE }</rights>
<?py for topic in posts: ?>
<entry>
<title>${ topic.title}</title>
<link rel=”alternate” type=”text/html” href=”http://#{curdomain}/p/#{topic.key().id()}” />
<id>tag:#{curdomain},#{topic.created.strftime(“%Y-%m-%d)”) }}:/p/#{topic.key().id()}</id>
<published>#{topic.created.strftime(“%Y-%m-%dT%H:%M:%SZ”)}</published>
<updated>#{topic.last_modified.strftime(“%Y-%m-%dT%H:%M:%SZ”)}</updated>
<author>
<name>#{topic.author_name}</name>
<uri>http://#{curdomain}/member/#{topic.author_name}</uri>
</author>
<content type=”html” xml:base=”http://#{curdomain}/” xml:lang=”en”><![CDATA[
#{urlize(myimg(nl2br(topic.short_con)))}
]]></content>
</entry>
<?py #endfor ?>
</feed>

是不是很想当然!

1,单行语句python代码 <?py xxxxx ?>

2,块Block语句 python代码

<?py if xxxx?>

XXXXX

<?py #endif?>

————————————————

<?py for xxx ?>

<?py #endfor?>

3, 变量 #{}不含HTML Escape转换 和 ${} 含HTML Escape转换

4, 条件判断表达式必须和if, while …等在一行写

5,Python代码的缩进必须是4个空格 (自版本1.0.0起,缩进不是必需的。)

6, <?PY ?>里是预编译的语句,这些语句只会被执行一次,里面的变量和函数不能被<?py ?>、#{}和${}所用,也不能使用<?py ?>和模板参数中的变量和函数。

7, #{{}}和KaTeX parse error: Expected 'EOF', got '#' at position 8: {{}}用法和#̲{}、{}类似,但只能使用<?PY ?>中的变量和函数。

8, 子模板可以用include()函数载入。

调用生成hmtl字串和习惯很相象

engine = tenjin.Engine(path=[os.path.join(‘template’, THEME), ‘template’], cache=tenjin.MemoryCacheStorage())
return engine.render(template, context, globals, layout)

**

Render Template

**

这是呈现模板文件的示例代码。

main.py: main program

## import modules and helper functions
import tenjin
#tenjin.set_template_encoding('cp932')   # template encoding
from tenjin.helpers import *

## context data
context = {
    'title': 'Tenjin Example',
    'items': ['<AAA>', 'B&B', '"CCC"'],
}

## create engine object
engine = tenjin.Engine(path=['views'])

## render template with context data
html = engine.render('page.pyhtml', context)
print(html)

结果

$ python main.py
<h2>Tenjin Example</h2>
<table>
  <tr class="odd">
    <td>&lt;AAA&gt;</td>
  </tr>
  <tr class="even">
    <td>B&amp;B</td>
  </tr>
  <tr class="odd">
    <td>&quot;CCC&quot;</td>
  </tr>
</table>

如果要指定模板编码,请调用tenjin.set_template_encoding()。默认编码为’utf-8’。

**

Show Converted Source Code

**

pyTenjin将模板文件转换为Python脚本并执行它。编译的Python脚本以文本格式自动保存到缓存文件中。

显示缓存的文件

$ ls views / page.pyhtml *
views / page.pyhtml views / page.pyhtml.cache
$ file views / page.pyhtml.cache
views / page.pyhtml.cache:text

您可以通过’ pytenjin -s’ 获得转换后的脚本。

显示Python代码

$ pytenjin -s views/page.pyhtml
_buf = []; _extend=_buf.extend;_to_str=to_str;_escape=escape; _extend(('''<h2>''', _escape(_to_str(title)), '''</h2>
<table>\n''', ));
i = 0
for item in items:
    i += 1
    klass = i % 2 and 'odd' or 'even'
    _extend(('''  <tr class="''', _to_str(klass), '''">
    <td>''', _escape(_to_str(item)), '''</td>
  </tr>\n''', ));
#endfor
_extend(('''</table>\n''', ));
print(''.join(_buf))

如果指定’ -sb’而不是’ -s’,则不会打印前导符(=’ _buf = [];’)和后置符号(=’ print("".join(_buf))’)。

or:
如何将模板文件转换为Python脚本

import tenjin
template = tenjin.Template('views/page.pyhtml')
print(template.script)

### or:
#template = tenjin.Template()
#with open('views/page.pyhtml') as f:
#    print(template.convert(f.read(), 'views/page.pyhtml'))

### or:
#engine = tenjin.Engine(path=['views'])
#print(engine.get_template('page.pyhtml').script)

**

布局模板

**
布局模板将帮助您为所有页面使用通用的HTML设计。
views/_layout.pyhtml

<!DOCTYPE>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>${title}</title>
  </head>
  <body>
#{_content}
  </body>
</html>

main.py

## import modules and helper functions
import tenjin
from tenjin.helpers import *

## context data
context = {
    'title': 'Tenjin Example',
    'items': ['<AAA>', 'B&B', '"CCC"'],
}

## cleate engine object
engine = tenjin.Engine(path=['views'], layout='_layout.pyhtml')

## render template with context data
html = engine.render('page.pyhtml', context)
print(html)

结果

$ python main.py
<!DOCTYPE>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Tenjin Example</title>
  </head>
  <body>
<h2>Tenjin Example</h2>
<table>
  <tr class="odd">
    <td>&lt;AAA&gt;</td>
  </tr>
  <tr class="even">
    <td>B&amp;B</td>
  </tr>
  <tr class="odd">
    <td>&quot;CCC&quot;</td>
  </tr>
</table>

  </body>
</html>

您可以使用render()方法指定其他布局模板文件。

##使用其他布局模板文件
engine.render('page.pyhtml',context,layout ='_ other_layout.pyhtml')

##不要使用布局模板文件
engine.render('page.pyhtml',context,layout = False)

**

上下文变量

**

’ _context’字典包含从主程序传递到模板文件的上下文数据。

使用’ _context’字典,您可以将任何数据从模板文件传递到主程序或布局模板文件。

views/_layout.pyhtml

<!DOCTYPE>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>${page_title}</title>
  </head>
  <body>
#{_content}
  </body>
</html>

views / page.pyhtml:将页面标题日期从模板传递到布局模板

<?py _context['page_title'] = 'Tenjin: Layout Template Example' ?>
<h2>${title}</h2>
<table>
<?py i = 0 ?>
<?py for item in items: ?>
<?py     i += 1 ?>
<?py     klass = i % 2 and 'odd' or 'even' ?>
  <tr class="#{klass}">
    <td>${item}</td>
  </tr>
<?py #endfor ?>
</table>

结果

$ python main.py
<!DOCTYPE>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Tenjin: Layout Template Example</title>
  </head>
  <body>
<h2>Tenjin Example</h2>
<table>
  <tr class="odd">
    <td>&lt;AAA&gt;</td>
  </tr>
  <tr class="even">
    <td>B&amp;B</td>
  </tr>
  <tr class="odd">
    <td>&quot;CCC&quot;</td>
  </tr>
</table>

  </body>
</html>

**

模板参数

**

为了便于阅读,建议在模板文件中声明上下文变量。
views/page.pyhtml

<?py #@ARGS title, items ?>
<?py _context['page_title'] = 'Tenjin: Layout Template Example' ?>
<h2>${title}</h2>
<table>
<?py i = 0 ?>
<?py for item in items: ?>
<?py     i += 1 ?>
<?py     klass = i % 2 and 'odd' or 'even' ?> 
  <tr class="#{klass}">
    <td>${item}</td>
  </tr>
<?py #endfor ?>
</table>

转换后的Python脚本

$ pytenjin -sb views/page.pyhtml
_extend=_buf.extend;_to_str=to_str;_escape=escape; title = _context.get('title'); items = _context.get('items'); 
_context['page_title'] = 'Tenjin: Layout Template Example'
_extend(('''<h2>''', _escape(_to_str(title)), '''</h2>
<table>\n''', ));
i = 0
for item in items:
    i += 1
    klass = i % 2 and 'odd' or 'even'
    _extend(('''  <tr class="''', _to_str(klass), '''">
    <td>''', _escape(_to_str(item)), '''</td>
  </tr>\n''', ));
#endfor
_extend(('''</table>\n''', ));

views/_layout.pyhtml

<?py #@ARGS _content, page_title ?>
<!DOCTYPE>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>${page_title}</title>
  </head>
  <body>
#{_content}
  </body>
</html>

转换后的Python脚本

$ pytenjin -sb views/_layout.pyhtml
_content = _context.get('_content'); page_title = _context.get('page_title'); 
_extend=_buf.extend;_to_str=to_str;_escape=escape; _extend(('''<!DOCTYPE>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>''', _escape(_to_str(page_title)), '''</title>
  </head>
  <body>
''', _to_str(_content), '''
  </body>
</html>\n''', ));

如果要指定上下文变量的默认值,请尝试。_context.get(‘varname’, defaultvalue)

<?PY
##如果未指定username,请使用“World”作为默认值。
username = _context.get('username','World')
?>
<p> Hello $ {username} </ p>

**

Include 部分模板

**

您可以通过include()辅助函数包含其他模板文件。

include(模板名称,** kwargs)
包括其他模板。template-name可以是文件名或模板短名称。kwargs作为局部变量传递给模板。
在以下示例中,布局模板包含页眉和页脚模板。

**

Template Short Name

**

如果设置模板后缀,则可以通过短名称指定模板,例如“ :page”而不是“ page.pyhtml”。请注意,模板短名称应以’ :’ 开头。

**

模板编码

**

如果要指定编码名称,请tenjin.set_template_encoding(‘utf-8’)在主程序中调用或将魔术注释添加到模板文件中。

Python 2.x

移步官网

Python 3.x

在Python 3.x中,string被视为unicode对象。所以pyTenjin处理字符串base(= unicode base)中的所有模板,字节数据按to_str()函数转换为str 。如果您未指定任何编码,Tenjin将使用’utf-8’编码作为默认值。

import tenjin
tenjin.set_template_encoding('cp932')   # or shift_jis
from tenjin.helpers import *

**

Helper Function

**

TODO 后续功能暂时没用到 下次更新

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值