OSDN Git Service

Regular updates
[twpd/master.git] / mako.md
1 ---
2 title: mako
3 category: Python
4 layout: 2017/sheet
5 ---
6
7 ### Basic usage
8
9 ```
10 Variable x has content: ${x}
11 Expression: ${x + 1}
12 Escaped for HTML: ${x | h}
13 ```
14
15 ### Control structures
16
17 ```html
18 % for x in range(5):
19     % if x % 2 == 0:
20     ${x} is even!
21     % else:
22     ${x} is odd!
23     % endif
24 % endfor
25 ```
26
27 ### Including Python code
28
29 ```python
30 <%
31     greeting = "Hello world!"
32     # arbitrary python code
33 %>
34
35 <%!
36 # arbitrary python code run at toplevel
37 # cannot access variables!
38
39 def sign_string(number):
40     if number > 0:
41         return "positive"
42     elif number < 0:
43         return "negative"
44     else:
45         return "zero"
46 %>
47 ```
48
49 ### Special blocks
50
51 ```html
52 <%text filter="h">
53     This is a raw block where ${nothing is evaluated}
54     <%
55         not even this
56     %>
57     and <html is escaped> too with "h" filter
58 </%text>
59
60 <%def name="myfunc(x)">
61     this is a reusable macro, with arguments: ${x}
62 </%def>
63
64 ${myfunc(42)}
65
66 <%doc>
67     this is a comment
68 </%doc>
69 ```
70
71 ### Inheritance
72
73 #### shared.html
74
75 ```html
76 <html>
77   <head>
78     <title><%block name="title" /></title>
79   </head>
80   <body>
81     <header><h1><%block name="title" /></h1></header>
82     <main>${self.body()}</main>
83   </body>
84 </html>
85 ```
86
87 #### home.html
88
89 ```html
90 <%inherit file="shared.html" />
91 <%block name="title">Welcome to my site</%block>
92
93 This is the body
94 ```
95
96 #### article.html
97
98 ```html
99 <%inherit file="shared.html" />
100 <%block name="title">${post.title}</%block>
101
102 ${post.content}
103 ```
104
105 ## Library
106
107 ### Basic usage
108
109 ```python
110 from mako.template import Template
111
112 mytemplate = Template("hello, ${name}!")
113 print(mytemplate.render(name="jack"))
114 ```