addCan 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 Versatile Concatenation Expert

In AnQiCMS template syntax,addfilters are a very practical tool, whose core function is to append or merge data. According to the official documentation,addThe filter can append content to be output, which behaves similarly to the Go language's+Operator. This means that it can not only perform addition operations on numbers, but more importantly, 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 exactly the key to our exploration of dynamic inline styles. WhenaddWhen the filter encounters data of different types, it attempts to perform intelligent conversion, 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 for building inline styles

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

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

  1. Get dynamic dataFrom the AnQiCMS backend or the context of the current page, obtain the data needed for style judgment or assignment (such as the number of views of the article, category ID, custom field values, etc.).
  2. Logical judgment and value preparation: Use the data obtained in the templateifDetermine the final CSS property value through statements and logical judgments. Store these dynamic values in template variables.
  3. UseaddConcatenate style strings using filters:The static CSS property names (such ascolor:)、dynamic property values (such asred)、and necessary connectors (such as;) to the same port of the AnQiCMS application instance (the default is usuallyaddFilter the components step by step to form a complete CSS style string.
  4. Apply tostyleProperty: Assign the concatenated style string to the HTML element'sstyleproperties.
  5. |safe[en]The use of filtersThis is the most critical step. AnQiCMS template engine, for security reasons, defaults to automatically escaping the output HTML content, which means that like</>/"Characters will be converted to HTML entities. In order for the concatenated CSS string to be correctly parsed as styles by the browser, it is necessary to add to the end of the final style string.|safeFilter, to inform the template engine that the content is safe and does not need to be escaped.

Practical Example: Dynamically Adjust Article Title Style

Assuming we want to dynamically adjust the color and font size of the article title based on the reading volume.When the reading volume exceeds 1000, the title is displayed in red and bold, otherwise it is displayed in blue.titlePaddingto 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 a string variable with fixed CSS text to create personalized styles.

UseaddFiltering and CSS styling concatenation best practices and**practice

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

  • Advantages:
    • High flexibilityCan achieve precise style control down to the element level, with style values directly sourced from data.
    • Direct and convenientFor a small number of simple dynamic style requirements, it is possible to avoid writing complex JavaScript or a large number of CSS classes.
    • Server-side generatedThe style is determined when the page is rendered, so there is no need for client-side JavaScript to modify it again, which helps with the first-screen loading and SEO.
  • Limitations:
    • Poor maintainability:Directly write styles in HTML elementsstyle(inline styles) in the attribute makes the code bulky and difficult to read, debug, and maintain.
    • CSS specificity issuesThe priority of inline styles is the highest, which may unintentionally override rules from external or internal style sheets, making style debugging difficult.
    • Performance impactThe inline style cannot be cached by the browser, which increases the size of the HTML file and affects the page loading performance to some extent.
    • Violates the separation principleContent is tightly coupled with style, which does not conform to the structure, presentation, and behavior in web development