Skip to content

Commit 64bb952

Browse files
committed
Document jinja macros
1 parent 76a2c87 commit 64bb952

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

components/substitutions.rst

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,71 @@ library is exposed as a module:
142142
To see what mathematical functions ara available,
143143
refer to `Python math library <https://docs.python.org/3/library/math.html>`_ documentation.
144144

145+
Macros
146+
^^^^^^
147+
148+
You can create reusable macros declaring them with the ``jinja`` component:
149+
150+
.. code-block:: yaml
151+
152+
jinja:
153+
macros:
154+
scale:
155+
parameters:
156+
x: 0 # default value of 0
157+
factor: 1.5 # default value of 1.5
158+
return: (x*factor) | round | int
159+
160+
These macros can then be invoked from within an expression:
161+
162+
.. code-block:: yaml
163+
164+
lvgl:
165+
widgets:
166+
- label:
167+
width: ${scale(200)} # 300
168+
height: ${scale(30, 2)} # 60
169+
170+
Macros can also capture substitution values:
171+
172+
.. code-block:: yaml
173+
174+
substitutions:
175+
display_scale: 1.5
176+
177+
jinja:
178+
macros:
179+
scale:
180+
parameters:
181+
x: 0
182+
factor: null
183+
return: (x * (display_scale if factor is none else factor)) | round | int
184+
185+
Instead of an immediate return expression, macros can define a full Jinja body that may contain Jinja statements:
186+
187+
.. code-block:: yaml
188+
189+
jinja:
190+
macros:
191+
get_glyphs:
192+
parameters:
193+
start: 0
194+
end: 0
195+
body: |
196+
# set ns = namespace(glyphs=[])
197+
# for code in range(start, end + 1)
198+
# set ns.glyphs = ns.glyphs + ["%c" | format(code)]
199+
# endfor
200+
${ ns.glyphs }
201+
202+
fonts:
203+
- file: "fonts/myfont.ttf"
204+
glyphs: ${ get_glyphs(0x3041, 0x304F) } # ぁ,あ,ぃ,い,ぅ ...
205+
206+
To understand what statements can be used in a macro body, please refer to `List of Control Structures <https://jinja.palletsprojects.com/en/stable/templates/#list-of-control-structures>`_
207+
and how they are used as `Line Statements <https://jinja.palletsprojects.com/en/stable/templates/#line-statements>`_ in Jinja documentation.
208+
209+
145210
.. _substitute-include-variables:
146211

147212
Substitute !include variables

0 commit comments

Comments
 (0)