用于重复标记的宏
编写模板函数以避免复制粘贴
用于重复标记的宏 是 CoddyKit 上的免费 Flask Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Flask Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Flask Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Repeated Markup Begs for a Function
When the same input field or card markup appears with small tweaks, copying it gets messy. A macro turns that pattern into a reusable function. 🛠️
What a Macro Is
A macro is a template function: you define markup once with parameters, then call it many times with different arguments.
Define a Macro
You declare a macro with a name and parameters, write its markup, and close it with endmacro. It is reusable from then on.
{% macro field(name) %}
<input name="{{ name }}">
{% endmacro %}Call a Macro
Invoke a macro like a function, passing arguments. Jinja2 renders the macro body with those values right where you call it.
{{ field("email") }}Parameters Customize Output
Macro parameters let one definition produce many variations, such as different input types or labels, from a single source of markup.
{% macro field(name, type="text") %}
<input name="{{ name }}" type="{{ type }}">
{% endmacro %}Default Argument Values
Give parameters defaults so common calls stay short. Callers override a default only when they need something different.
{{ field("age", type="number") }}Keep Macros in Their Own File
Store shared macros in a file like forms.html so many templates can import and reuse the same helpers.
{% import "forms.html" as forms %}Import Then Call
After import, call a macro through its namespace. This keeps your macro library separate from the page using it.
{{ forms.field("email") }}Import Specific Macros
Use from import to pull just the macros you need by name, keeping the template clean and the intent obvious.
{% from "forms.html" import field %}Macros vs Includes
An include drops fixed markup; a macro takes arguments and varies its output. Reach for macros when the snippet must change per call.
DRY Templates at Last
Macros remove copy-paste from your templates: fix the field markup once and every call site updates. That is templating done right. ✨
Quick Check
What makes a macro different from an include?
Recap: Macros
A macro is a reusable, parameterized template function. Define it once, import it, and call it anywhere to keep templates DRY. 🎯
常见问题解答
「用于重复标记的宏」课时是免费的吗?
是的 — 「用于重复标记的宏」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Flask Academy 课程的其余内容,请升级到 CoddyKit PRO。 Flask Academy 课程共包含 4 节课。
「用于重复标记的宏」这节课中我会学到什么?
编写模板函数以避免复制粘贴 你通过在浏览器中直接运行的动手代码来练习 Flask Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Flask Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Flask Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「用于重复标记的宏」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Flask Academy 课中编写并运行代码吗?
能。每节 Flask Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 使用块定义基础模板
- 在子页面中扩展基础模板
- 包含可复用的局部模板
- 用于重复标记的宏