AnQiCMS provides users with great convenience with its flexible and powerful template engine, allowing content presentation to be highly customized according to actual needs.In daily template development, we often encounter scenarios where we need to dynamically adjust the page performance based on backend data, such as changing the title color based on the article reading volume or displaying different background styles based on user permissions.At this moment, we might think, AnQiCMS templates built-inaddCan the filter be used to concatenate CSS style strings to achieve these dynamic inline style controls? This article will delve into this feature.

addFilter: The flexible concatenation master

In the template syntax of AnQiCMS,addA filter is a very practical tool, its core function is to append or merge data. According to the official documentation,addThe filter can append content to be output, its behavior is similar to that in Go language.+An operator. This means it can not only perform addition operations on numbers, but it can also concatenate multiple strings.

For example, if you want to concatenate the words '安企' and 'CMS', you can do it directly like this: {{"安企"|add:"CMS"}}The result will be "AnQi CMS". This ability to concatenate strings is the key to exploring dynamic inline styles. WhenaddThe filter encounters different types of data and tries to perform intelligent conversions, for example, when a number is concatenated with a string, the number is converted to a string before the connection, which provides great flexibility for our style construction.

The logic of constructing dynamic inline styles

CSS styles are essentially composed of a series of strings, for examplecolor: red; font-size: 16px;Since.addThe filter can efficiently concatenate strings, so of course it can be used to concatenate these CSS property names, colons, dynamic values, and semicolons to dynamically generate complete CSS style declarations.

The basic steps to implement dynamic inline styles are as follows:

  1. Get dynamic data: Obtain data needed for style judgment or assignment from the AnQiCMS backend or the context of the current page (such as the reading volume of articles, category ID, custom field values, etc).
  2. Logical judgment and value preparation: Use the data obtained in the templateifEvaluate statements and logical conditions to determine the final CSS property value. Store these dynamic values in template variables.
  3. UseaddFilter concatenates the style string.: Static CSS property names (such ascolor:), dynamic property values (such asred), and necessary connectors (such as;PassedaddFilter progressively to form a complete CSS style string.
  4. Apply tostyleproperty: Assign the concatenated style string to the HTML element'sstyleProperty.
  5. |safeUse of filtersThis is the most critical step. AnQiCMS template engine defaults to automatically escaping the output HTML content, which means that like</>/"Characters are converted to HTML entities. To ensure that the concatenated CSS string is correctly parsed as styles by the browser, it must be added to the end of the final style string.|safeA filter to inform the template engine that the content is safe and does not need to be escaped.

Practical example: Dynamically adjust the style of the article title

Assuming we want to dynamically adjust the color and font size of the title based on the number of article views.When the reading volume exceeds 1000, the title is displayed in red and bold, otherwise it is displayed in blue.At the same time, we also hope to base it on another custom fieldtitlePaddingTo set the inner padding of the title.

{# 假设我们正在文章详情页,并已通过 archiveDetail 标签获取了文章对象 #}
{% archiveDetail articleTitle with name="Title" %} {# 获取文章标题 #}
{% archiveDetail articleViews with name="Views" %} {# 获取文章阅读量 #}
{% archiveDetail articlePadding with name="titlePadding" %} {# 获取自定义内边距值 #}

{# 根据阅读量设置动态颜色和字体粗细 #}
{% set dynamicColor = "blue" %}
{% set dynamicWeight = "normal" %}
{% if articleViews > 1000 %}
    {% set dynamicColor = "red" %}
    {% set dynamicWeight = "bold" %}
{% endif %}

{# 如果自定义内边距有值,则使用,否则默认0px #}
{% set dynamicPadding = "0px" %}
{% if articlePadding %}
    {% set dynamicPadding = articlePadding|add:"px" %} {# 假设 articlePadding 是数字,这里拼接 "px" #}
{% endif %}

{# 使用 add 过滤器拼接 CSS 样式字符串,并应用到 style 属性,最后使用 |safe 确保不被转义 #}
<h1 style="{{ "color:"|add:dynamicColor|add:";"|add:"font-weight:"|add:dynamicWeight|add:";"|add:"padding:"|add:dynamicPadding|add:";"|safe }}">
    {{ articleTitle }}
</h1>

{# 另一个更复杂的例子:动态背景色与固定背景图的结合 #}
{% set sectionBgColor = "rgba(240, 240, 240, 0.8)" %}
{% set sectionBgImage = "url('/static/images/hero-bg.jpg')" %}
<section style="{{ "background-color:"|add:sectionBgColor|add:";"|add:"background-image:"|add:sectionBgImage|add:";background-repeat: no-repeat; background-size: cover;"|safe }}">
    <p>这是一个拥有动态背景色和背景图片的区域。</p>
</section>

In the above example, we sawaddHow the filter seamlessly combines string variables with fixed CSS text to create personalized styles.

UseaddFiltering and concatenating CSS styles: Notes and **practical**

ThoughaddThe filter provides powerful flexibility in concatenating dynamic CSS style strings, but this approach also comes with some considerations:

  • Advantage:
    • High flexibility: Can achieve precise style control at the element level, style values are directly derived from data.
    • Direct and convenientFor simple dynamic style needs, you can avoid writing complex JavaScript or a large number of CSS classes.
    • server-side generatedThe style is already determined at page rendering time, no need for client-side JavaScript to modify it twice, which helps with first-screen loading and SEO.
  • Limitation:
    • Poor maintainability: Write the style directly in the HTML element'sstyleattribute (inline style) makes the code bulky, difficult to read, debug, and maintain.
    • CSS priority issue: Inline styles have the highest priority and may unintentionally override rules from external or internal style sheets, making style debugging difficult.
    • Performance impactInline styles cannot be cached by the browser, which increases the size of the HTML file and affects page loading performance to some extent.
    • Violates the separation principle.The content and style are tightly coupled, which does not conform to the structure, presentation, and behavior in web development