As an experienced website operations expert, I am well aware in my daily work that the quality of template writing in the Content Management System (CMS) is crucial for the overall performance of the website.AnQiCMS with its concise and efficient architecture and the performance advantages of the Go language, provides us with powerful content management capabilities.However, even the most powerful tools require good habits to maximize their potential, and the 'whitespace control' during template writing is a detail often overlooked yet profoundly influential.
Today, let's delve into how to develop good blank control habits in the process of writing AnQiCMS templates, making your templates cleaner and more efficient.
Why is template whitespace control so important?
You may be puzzled, what's the big deal about a few extra spaces or blank lines? But in fact, good white space control habits not only concern the 'face' of template code, but also affect its 'interior':
- Improve readability and maintainability:Uniform spacing and clear hierarchy make template code easy to read.Whether it is your own future review or the reading of others in team collaboration, it can greatly reduce the cost of understanding and improve maintenance efficiency.
- Easy to debug and troubleshoot issues:When a page has unexpected layout or rendering issues, chaotic whitespace is often the 'scapegoat'. Standard whitespace can help you locate the boundaries of code blocks more quickly, narrowing the scope of troubleshooting.
- Ensure the purity of HTML output:Especially when dealing with inline elements(
<span>/<a>When using certain CSS layouts, excessive line breaks or spaces in the template may result in unnecessary spacing in the final generated HTML, which can affect the visual appearance of the page.Although modern browsers have a good tolerance for such issues, forming the habit of clean output can save you from detours when encountering tricky compatibility issues. - The cornerstone of team collaboration:In a team project, a unified whitespace control specification is an important link to ensure the consistency of code style.It reduces formatting conflicts caused by individual habits, allowing code reviews to focus on business logic rather than trivial formatting issues.
The core principle of AnQiCMS template blank control
AnQiCMS templates use syntax similar to the Django template engine, with.htmlas the file extension, and follow a clear directory structure (refer todesign-convention.mdanddesign-director.md)。Understanding its grammatical features is the premise for effective blank control.
- Consistency is the golden rule:No matter whether you prefer a compact format or a loose layout, the most important thing is to maintain consistency throughout the entire project and even the team.Choose a style and stick to it, it's much better than frequently switching or mixing it up randomly.
- Logical grouping is separated by blank lines:Like writing an article, divide the template code into logical paragraphs. Separate different functional modules, loops, and conditional judgment blocks with blank lines. For example, in defining
{% categoryList %}After, you can leave a blank line and start{% for item in categories %}. - Indented clearly:Use consistent indentation (for example, 2 or 4 spaces, or tabs) to reflect the nesting relationship and hierarchical logic of HTML elements. In AnQiCMS templates,
<head>/<body>such HTML tags, as well{% if %}/{% for %}such control flow tags, should have clear indentation.
Practical blank control techniques in AnQiCMS templates
AnQiCMS template engine provides some very practical features that can help us precisely control the white space of the output.
1. Precisely control the white space of the output symbol.{%-and-%}
This is the most direct and powerful blank control tool in the AnQiCMS template, intag-remove.mdThere is a detailed description. By default, the template engine will also output the line breaks and spaces around the tags to the final HTML.And by adding hyphens on both sides of the tag (-), We can tell the engine to remove these extra spaces:
{%- tag -%}Remove all whitespace (including newline characters) from both sides of the tag.{%- tag %}Remove only the whitespace from the left side of the tag.{% tag -%}Remove only the whitespace from the right side of the tag.
Example:Assuming we have a loop, if we do not control the blank, many blank lines may be generated.
{# 默认输出,可能产生多余空行 #}
<ul>
{% for item in archives %}
<li>{{ item.Title }}</li>
{% endfor %}
</ul>
{# 使用 {% -%} 精准控制空白 #}
<ul>
{%- for item in archives -%}
<li>{{ item.Title }}</li>
{%- endfor -%}
</ul>
In the above example, the second method generates a more compact HTML output, avoiding<li>unnecessary line breaks before and after tags. Similarly, inifthe statement also applies:
<div>
{%- if condition -%}
<p>这是条件内容</p>
{%- else -%}
<p>这是其他内容</p>
{%- endif -%}
</div>
This will ensuredivinternallypLabels will not beifcaused by labels to have extra line breaks or spaces.
2. Make good use ofinclude,extends,macroorganizational structure
tag-tags.mdThe document details the followinginclude/extendsandmacroThese auxiliary tags are not only for code reuse, but also an indirect means of achieving good white space control:
extends(Template Inheritance):Define a basic layoutbase.htmlincluding the overall structure of the page, CSS/JS references, navigation, and other common parts. The variable content is wrapped in{% block %}tags. Sub-templates inherit and override{% extends 'base.html' %}inheritance and rewritingblockThis makes each template focus only on the blank control of its own core content, avoiding repetition and redundancy.include(Code snippet introduced):Split the header, footer, sidebar, or any reusable small block of code into separate.htmla file, and then through{% include "partial/header.html" %}introduce. Each fileincludecan be independently controlled for whitespace, without interfering with each other. UsewithPass variables with attention to their variable scope, which also helps keep local code clear.macro(Macro function):When you have a piece of code that needs to be frequently repeated and has a similar structure (such as list items, card display), you can define it as a macro.Macros only accept passed parameters, which naturally limits the scope of variables within them, encouraging purer and more controllable whitespace usage.
By these structured tags, you can decompose complex pages into modular components, making the control of whitespace within each component simpler and more centralized.
3. Standard Indentation and Blank Line Strategy
HTML Structure Indentation:Maintain standard HTML indentation habits. For example, nested,
<div>/<ul>/<li>Tags, each level increases an indentation.Template logic indentation:
{% if %}/{% for %}Blocks of code inside control flow tags should also be indented to align with the controlled HTML content or variable output.<nav> {%- navList navs -%} <ul> {%- for item in navs -%} <li{% if item.IsCurrent %} class="active"{% endif %}> <a href="{{ item.Link }}">{{ item.Title }}</a> {%- if item.NavList -%} <dl> {%- for inner in item.NavList -%} <dd{% if inner.IsCurrent %} class="active"{% endif %}> <a href="{{ inner.Link }}">{{ inner.Title }}</a> </dd> {%- endfor -%} </dl> {%- endif -%} </li> {%- endfor -%} </ul> {%- endnavList -%} </nav>This example clearly demonstrates how to combine indentation and
{%- %}to control the output of complex navigation.alignment of tag attributes:If a tag has multiple attributes, consider placing each attribute on a new line and aligning it to improve readability, especially when the attribute value is long.
<img src="{{ item.Logo }}" alt="{{ item.Alt }}" class="lazyload" data-src="{{ item.LazyLoadSrc }}" />
4. Usage of comments (tag-tags.md)
AnQiCMS supports two comment styles:
{# 单行注释 #}: Does not output to the final HTML.{% comment %} 多行注释 {% endcomment %}: Does not output to the final HTML.
Comments themselves do not affect HTML output, but their existence is to improve the readability of the code.Using comments reasonably to explain complex logic or module functions can help others (or future you) understand the code structure faster, thereby better following and maintaining the blank control.
Tools and methods for cultivating habits
- Automatic formatting of code editors/IDEs:Make full use of your code editor's (such as VS Code, Sublime Text) auto-formatting feature.Configure the formatting rules for HTML/template language and develop the habit of auto-formatting when saving.Although for templates of AnQiCMS with specific syntax, there may not be a ready-to-use perfect formatting tool, but the basic HTML formatting rules can also help a lot