From ec1223800fe3342b7b21f4421aaa3ca86dfe8d47 Mon Sep 17 00:00:00 2001 From: hydrargyrum Date: Mon, 27 Sep 2021 03:29:02 +0200 Subject: [PATCH] Add mako cheatsheet (#1687) * Add mako cheatsheet * Update mako.md Co-authored-by: Rico Sta. Cruz --- mako.md | 114 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 mako.md diff --git a/mako.md b/mako.md new file mode 100644 index 00000000..f4c9e0be --- /dev/null +++ b/mako.md @@ -0,0 +1,114 @@ +--- +title: mako +category: python +layout: 2017/sheet +--- + +### Basic usage + +``` +Variable x has content: ${x} +Expression: ${x + 1} +Escaped for HTML: ${x | h} +``` + +### Control structures + +```html +% for x in range(5): + % if x % 2 == 0: + ${x} is even! + % else: + ${x} is odd! + % endif +% endfor +``` + +### Including Python code + +```python +<% + greeting = "Hello world!" + # arbitrary python code +%> + +<%! +# arbitrary python code run at toplevel +# cannot access variables! + +def sign_string(number): + if number > 0: + return "positive" + elif number < 0: + return "negative" + else: + return "zero" +%> +``` + +### Special blocks + +```html +<%text filter="h"> + This is a raw block where ${nothing is evaluated} + <% + not even this + %> + and too with "h" filter + + +<%def name="myfunc(x)"> + this is a reusable macro, with arguments: ${x} + + +${myfunc(42)} + +<%doc> + this is a comment + +``` + +### Inheritance + +#### shared.html + +```html + + + <%block name="title" /> + + +

<%block name="title" />

+
${self.body()}
+ + +``` + +#### home.html + +```html +<%inherit file="shared.html" /> +<%block name="title">Welcome to my site + +This is the body +``` + +#### article.html + +```html +<%inherit file="shared.html" /> +<%block name="title">${post.title} + +${post.content} +``` + +## Library + +### Basic usage + +```python +from mako.template import Template + +mytemplate = Template("hello, ${name}!") +print(mytemplate.render(name="jack")) +```