From f0f4f05c92dab47987cd94c7a06a1f81f1c34ac7 Mon Sep 17 00:00:00 2001 From: hydrargyrum Date: Mon, 27 Sep 2021 03:14:30 +0200 Subject: [PATCH] Add Jinja cheatsheet (#1688) Co-authored-by: Rico Sta. Cruz --- jinja.md | 101 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ jinja2.md | 5 +++ 2 files changed, 106 insertions(+) create mode 100644 jinja.md create mode 100644 jinja2.md diff --git a/jinja.md b/jinja.md new file mode 100644 index 000000000..63c857a79 --- /dev/null +++ b/jinja.md @@ -0,0 +1,101 @@ +--- +title: jinja +category: python +layout: 2017/sheet +--- + +{% raw %} +### Basic usage + +``` +- variable x has content: {{ x }} +- expression: {{ x + 1 }} +- escaped for HTML: {{ x | e }} +``` + +### Control structures + +``` +{% for x in range(5) %} + {% if x % 2 == 0 %} + {{ x }} is even! + {% else %} + {{ x }} is odd! + {% endif %} +{% endfor %} +``` + +### Whitespace trimming + +``` +these are +{{ "three" }} +lines. + +this is conc +{{- "at" -}} +enated. +``` + +### Special blocks + +``` +{% filter e %}{% endraw %} +{ {%- if 0 -%}{%- endif -%} % raw %} +{%- raw -%} + This is a raw block where {{nothing is evaluated}} + {% not even this %} + and too with "e" filter +{% endraw %} +{ {%- if 0 -%}{%- endif -%} % endraw %}{% raw %} +{% endfilter %} + +{% macro myfunc(x) %} + this is a reusable macro, with arguments: {{x}} +{% endmacro %} + +{{ myfunc(42) }} + +{# +this is a comment +#} +``` + + +### Inheritance + +#### shared.html + +``` + + + {%block title %}{% endblock %} + + +

{% block title %}{% endblock %}

+
{% block content %}{% endblock %}
+ + +``` + +#### home.html + +``` +{% extends "shared.html" %} +{% block title %}Welcome to my site{% endblock %} +{% block content %} +This is the body +{% endblock %} +``` + +## Library + +### Basic usage + +```python +from jinja2 import Template +template = Template('Hello {{ name }}!') +template.render(name='John Doe') == u'Hello John Doe!' +``` + +{% endraw %} diff --git a/jinja2.md b/jinja2.md new file mode 100644 index 000000000..5ec30e864 --- /dev/null +++ b/jinja2.md @@ -0,0 +1,5 @@ +--- +title: jinja +category: python +redirect_to: /jinja +---