How to flexibly call and display custom fields in front-end templates?

When using Anqin CMS to manage website content, its powerful content model and custom field functions provide great flexibility for the website's personalized needs.At times, we not only need to publish regular article titles, content, etc., but also need to add some unique information for specific types of articles or products, such as the author of the article, product model, launch date, and special selling points.This information is exactly implemented through content model custom fields.How can these custom fields be flexibly called and displayed in the website front-end template?This is the issue we are to delve into today.

Understanding content models and custom fields

First, let's briefly review the concept of content model and custom fields in Anqi CMS.The content model, as the name implies, is like a 'skeleton' or 'template' custom-made for different types of content.For example, you can create an 'article model' for blog posts, and a 'product model' for displaying product information.Each model includes a series of standard fields (such as title, content, classification, etc.), and Anqi CMS allows us to add "custom fields" for each model.

The types of custom fields are very rich, including single-line text (for short text input, such as author name), numbers (for prices, inventory, etc.), multi-line text (for long descriptions), single selection, multiple selection, and drop-down selection (for selecting preset options).In the background, we can easily configure these custom fields for a content model, setting their names, field names, types, whether they are required, and default values.After these settings are completed, when we publish content under this model, we can see the corresponding custom field input box, making it convenient to enter various personalized data.

Basics of front-end template calls

The front-end template system of AnQi CMS is based on Django template engine syntax, which means it has a powerful and intuitive variable and tag calling mechanism. In the template file, we use double curly braces{{变量}}Output the value of the variable, using single curly braces and the percent sign{% 标签 %}To perform logical control or call specific functions. The value of custom fields is essentially part of the content data as well, and it also follows this set of rules.

All template files are stored in/templateUnder the directory, static resources (CSS, JS, images) are/public/static/. Variable names usually follow camel case (for examplearchive.Title), which is convenient for understanding and use.

Flexibly call the core tags of custom fields

In AnQi CMS, calling custom fields of the content model mainly depends on two core tags:archiveDetailandarchiveParams.

1. UsearchiveDetailTags call specific custom fields

When you know the name of the custom field's 'reference field'archiveDetailThe tag is a direct and efficient calling method. This tag is mainly used to obtain detailed data of the current document or a specified document on the document detail page.

Calling method: {% archiveDetail 变量名称 with name="自定义字段的调用字段名" %}

Among them,变量名称can be omitted, if omitted, the label will directly output the value of the field. If specified变量名称, then the value obtained can be assigned to this variable, and used in the template later by{{变量名称}}.

Example scenario:Assuming we added a named "author" field to the "article model":author)" field on a single line text field, and added a named "product batch number (field call:batch_number)" field on a single line text field."}

  • Call the author on the article detail page:

    <p>作者:{% archiveDetail with name="author" %}</p>
    

    Or assign the value to a variable and use it later:

    {% archiveDetail articleAuthor with name="author" %}
    <p>作者:{{ articleAuthor }}</p>
    
  • Call the product batch number on the product details page:

    <p>产品批次号:{% archiveDetail with name="batch_number" %}</p>
    

Handle special field types:

  • Group image field (for example named)')product_imagesCustom field of the group image):The group field usually returns an array of image URLs. In this case, you need to loop through to display all images:

    {% archiveDetail productImages with name="product_images" %}
    <div class="product-gallery">
        {% for imgUrl in productImages %}
            <img src="{{ imgUrl }}" alt="产品图片" />
        {% endfor %}
    </div>
    
  • Rich text field (such as namedfull_descriptionThe multi-line text field, using Markdown or rich text editor):If the custom field stores HTML content or Markdown content, direct output may display the original tags. In this case, it is necessary to usesafeOr filter.renderFilter to parse HTML or render Markdown:

    <div class="full-description">
        {% archiveDetail productDescription with name="full_description" %}
        {{ productDescription|safe }}  {# 如果是HTML内容 #}
        {# 或者 {{ productDescription|render|safe }} 如果是Markdown内容 #}
    </div>
    

    renderThe filter will convert Markdown content to HTML,safeThe filter ensures that HTML content is displayed directly without being escaped.

2. UsearchiveParamsLoop through all custom fields with tags.

When you are unsure about the custom fields or need to display all custom fields and their values in a uniform way,archiveParamsLabels are very useful. They can get all custom parameters of the current document or a specified document.

Calling method: {% archiveParams 变量名称 with id="文档ID" sorted=true %}

  • 变量名称: Used to receive an array or Map object of all custom fields.
  • idOptional parameter, used to specify the custom field of the document to be retrieved. If omitted, the document of the current page is retrieved by default.
  • sortedOptional parameter, default istrue.
    • sorted=true(Default):变量名称It will be an ordered array containingName(parameter name, that is, the Chinese name) andValue(parameter value). This method is suitable forforto loop through and display.
    • sorted=false:变量名称It will be an unordered Map object, you can use变量名称.调用字段名.Nameand变量名称.调用字段名.ValueDirectly access specific fields.

Example scenario:We hope to display all product parameters on the product details page, and these parameters may be dynamically added or modified on the backend.

  • Display all custom fields in an ordered array:

    <div class="product-parameters">
        <h3>产品参数</h3>
        <ul>
            {% archiveParams params %} {# 默认 sorted=true #}
            {% for item in params %}
                <li>
                    <span>{{ item.Name }}:</span>
                    <span>{{ item.Value }}</span>
                </li>
            {% endfor %}
            {% endarchiveParams %}
        </ul>
    </div>
    

    This method is very suitable for displaying generic parameters, without knowing the specific field names of each field.

  • Access specific custom fields directly in an unordered Map:Assuming we havematerial(Material) andweight(Weight) two custom fields.

    <div class="product-specs">
        {% archiveParams productSpecs with sorted=false %}
        <p>材质:{{ productSpecs.material.Value }}</p>
        <p>重量:{{ productSpecs.weight.Value }}</p>
        {% endarchiveParams %}
    </div>
    

    The advantage of this method is that it can directly obtain the field name by calling the custom field, but it needs to ensure that the called field name of the custom field is known and stable.

Build in accordance with the actual page

When building a website in practice, the flexible invocation of custom fields can greatly enhance the richness of content display.For example, a product page of an e-commerce website can use custom fields to display various product properties: color, size, material, stock, origin, etc.An article page of a content website, which can display the originality statement of the article, the source of citation, the column it belongs to, and so on.

Common steps:

  1. Determine the content type:What types of content are needed, such as news, products, cases, etc.
  2. Create/Edit content model:Create or edit the corresponding content model in the AnQi CMS backend.
  3. Add custom field:According to the needs of the content type, add necessary custom fields to the model and carefully define the names and types of 'invoked fields'.
  4. Design the front-end template: Intemplatecorresponding template file in the directory (for example, article detail page)archive/detail.htmlUse it inarchiveDetailorarchiveParamstags to call and display these custom fields
  5. Content release:When publishing content in the background, fill in data for custom fields.

By following these steps, we can fully utilize the customized field function of Anqi CMS to build highly customized and expressive website content.

Frequently Asked Questions (FAQ)

  1. Why am IarchiveListCannot directly pass in the loopitem.我的自定义字段Call? archiveListTags are mainly used to obtain common basic fields of document lists, such as titles, links, descriptions, etc. To maintain the efficiency of list queries and data brevity, it defaults to not including all custom fields.itemIn the object. If you need to display a custom field on the list page, the recommended practice is toarchiveListWithin a loop, for eachitem, usingarchiveDetailtag (viaid=item.Idparameters to specify the current document) orarchiveParamsLabel to retrieve and display its custom fields. However, if the value of the custom field is only used as a filter condition or simple prompt on the list page, it can also be considered to be set through the background settings, inarchiveListThe query parameters are explicitly specified, but this usually adds complexity to the database query.

  2. I have a custom field that is a checkbox. How can I display all selected values on the front end?Check box type custom fields are usually stored on the backend as strings containing multiple values (such as值1,值2,值3) or arrays. You can use them in the frontend template.splitThe filter splits this string by delimiter (usually comma,) into an array, then goes throughforLoop through this array to display all selected values. For example:

    {% archiveDetail selectedOptions with name="my_multi_select_field" %}
    <ul>
    {% for option in selectedOptions|split:"," %}
        <li>{{ option }}</li>
    {% endfor %}
    </ul>
    
  3. I have customized a rich text editor field, why does it display as text with HTML tags directly?The content stored in a rich text editor is usually with