Теги и Фильтры Шаблонов Портала Поддержки

Последнее изменение:


Шаблоны портала UserEcho используют теги и фильтры для работы с данными шаблонов.

Теги шаблонов

if ... elif ... else ... endif

The {% if %} tag evaluates a variable, and if that variable is “true” (i.e. exists, is not empty, and is not a false boolean value) the contents of the block are output:

{% if portal.section == "login" %}
    This is login page
{% elif portal.section == "password_reset" %}
    This is password reset page
{% else %}
    This is some page
{% endif %}
As you can see, theif tag may take one or several {% elif %} clauses, as well as an {% else %} clause that will be displayed if all previous conditions fail. These clauses are optional.


Boolean operators

if tags may use and, or or not to test a number of variables or to negate a given variable:

{% if portal.section == "login" and portal.user %}
    The user is authenticated
{% endif %}

{% if not portal.user %}
    User is not authenticated
{% endif %}

{% if portal.section == "login" or portal.section == "password_reset" %}
    Common block for login and password reset
{% endif %}

{% if x and y or z %}

will be interpreted like:

if (x and y) or z

Use of actual parentheses in the if tag is invalid syntax. If you need them to indicate precedence, you should use nested if tags.

if tags may also use the operators ==, !=, <, >, <=, >=, in, not in, is, and is not which work as follows:

== operator

Equality. Example:

{% if somevar == "x" %}
  This appears if variable somevar equals the string "x"
{% endif %}
!= operator

Inequality. Example:

{% if somevar != "x" %}
  This appears if variable somevar does not equal the string "x",
  or if somevar is not found in the context
{% endif %}
< operator

Less than. Example:

{% if somevar < 100 %}
  This appears if variable somevar is less than 100.
{% endif %}
> operator

Greater than. Example:

{% if somevar > 0 %}
  This appears if variable somevar is greater than 0.
{% endif %}
<= operator

Less than or equal to. Example:

{% if somevar <= 100 %}
  This appears if variable somevar is less than 100 or equal to 100.
{% endif %}
>= operator

Greater than or equal to. Example:

{% if somevar >= 1 %}
  This appears if variable somevar is greater than 1 or equal to 1.
{% endif %}
in operator

Contained within. This operator is supported by many Python containers to test whether the given value is in the container. The following are some examples of how x in y will be interpreted:

{% if "bc" in "abcdef" %}
  This appears since "bc" is a substring of "abcdef"
{% endif %}

{% if "hello" in greetings %}
  If greetings is a list or set, one element of which is the string
  "hello", this will appear.
{% endif %}

{% if user in users %}
  If users is a QuerySet, this will appear if user is an
  instance that belongs to the QuerySet.
{% endif %}
not in operator

Not contained within. This is the negation of the in operator.

is operator

Object identity. Tests if two values are the same object. Example:

{% if somevar is True %}
  This appears if and only if somevar is True.
{% endif %}

{% if somevar is None %}
  This appears if somevar is None, or if somevar is not found in the context.
{% endif %}
is not operator

Negated object identity. Tests if two values are not the same object. This is the negation of the is operator. Example:

{% if somevar is not True %}
  This appears if somevar is not True, or if somevar is not found in the
  context.
{% endif %}

{% if somevar is not None %}
  This appears if and only if somevar is not None.
{% endif %}


Filters

You can also use filters in the if expression. For example:

{% if messages|length >= 100 %}
   You have lots of messages today!
{% endif %}


Complex expressions


All of the above can be combined to form complex expressions. For such expressions, it can be important to know how the operators are grouped when the expression is evaluated - that is, the precedence rules. The precedence of the operators, from lowest to highest, is as follows:

  • or
  • and
  • not
  • in
  • ==, !=, <, >, <=, >=

So, for example, the following complex if tag:

{% if a == b or c == d and e %}

…will be interpreted as:

(a == b) or ((c == d) and e)

If you need different precedence, you will need to use nested if tags. Sometimes that is better for clarity anyway, for the sake of those who do not know the precedence rules.

The comparison operators cannot be ‘chained’ like in Python or in mathematical notation. For example, instead of using:

{% if a > b > c %}  (WRONG)

you should use:

{% if a > b and b > c %}


for ... empty ... endfor

Loops over each item in an array, making the item available in a context variable. For example, to display a list of athletes provided in item_list:

<ul>
{% for item in item_list %}
    <li>{{ item.name }}</li>
{% endfor %}
</ul>

You can loop over a list in reverse by using {% for obj in list reversed %}.

If you need to loop over a list of lists, you can unpack the values in each sublist into individual variables. For example, if your context contains a list of (x,y) coordinates called points, you could use the following to output the list of points:

{% for x, y in points %}
    There is a point at {{ x }},{{ y }}
{% endfor %}

This can also be useful if you need to access the items in a dictionary. For example, if your context contained a dictionary data, the following would display the keys and values of the dictionary:

{% for key, value in data.items %}
    {{ key }}: {{ value }}
{% endfor %}

The for loop sets a number of variables available within the loop:

Variable Description
forloop.counter The current iteration of the loop (1-indexed)
forloop.counter0 The current iteration of the loop (0-indexed)
forloop.revcounter The number of iterations from the end of the loop (1-indexed)
forloop.revcounter0 The number of iterations from the end of the loop (0-indexed)
forloop.first True if this is the first time through the loop
forloop.last True if this is the last time through the loop
forloop.parentloop For nested loops, this is the loop surrounding the current one

The for tag can take an optional {% empty %} clause whose text is displayed if the given array is empty or could not be found:

<ul>
{% for item in item_list %}
    <li>{{ item.name }}</li>
{% empty %}
    <li>Sorry, no items in this list.</li>
{% endfor %}
</ul>

with ... endwith

Caches a complex variable under a simpler name. This is useful when you need to have some variable to be accessible by another name (ex: topic as item).

For example:

{% with forum=topic.forum item=topic %}
    Forum: {{ forum.name }}, Topic: {{ item.header }}
{% endwith %}

The populated variable is only available between the {% with %} and {% endwith %} tags.


comment ... endcomment

comment

Ignores everything between {% comment %} and {% endcomment %}. For example, this is useful when commenting out some code temporary or add some comments to existing code.

Sample usage:

{% comment %}
    This is commented text, not visible on the page
{% endcomment %}

comment tags cannot be nested.

trans

The {% trans %} template tag translates either a constant string (enclosed in single or double quotes) or variable content:

<title>{% trans "This is the title." %}</title>
<title>{% trans myvar %}</title>

If you’d like to retrieve a translated string without displaying it, you can use the following syntax:

{% trans "This is the title" as the_title %}

<title>{{ the_title }}</title>
<meta name="description" content="{{ the_title }}">

Also trans tag allows you to mark complex sentences consisting of literals and variable content for translation by making use of placeholders:

{% trans "This string will have {{ value }} inside." %}

To translate a template expression – say, accessing object attributes or using template filters – you need to bind the expression to a local variable for use within the translation block. Examples:

{% trans "That will cost ${{ amount }}." with amount=article.price %}

You can use multiple expressions inside a single trans tag:

{% trans "This is {{ book_t }} by {{ author_t }}"  with book_t=book|title author_t=author|title %}

This tag also provides for pluralization. To use it:

  • Designate and bind a counter value with the name count. This value will be the one used to select the right plural form.
  • Specify both the singular and plural forms. Provide plural form right after singular or in one argument as a var (list [singular, plural]).

An example:

{% trans "There is only one {{ name }} object." "There are {{ counter }} {{ name }} objects." count counter=list|length %}

If some var example_var has both strings in array as  ["There is only one {{ name }} object.", "There are {{ counter }} {{ name }} objects."] you can pass that var directly

{% trans example_var count counter=list|length %}

A more complex example:

{% trans "That will cost $ {{ amount }} per year." "That will cost $ {{ amount }} per {{ counter }} years." with amount=article.price count counter=i.length %}

paginate ... endpaginate

The {% paginate %} template tag helps to build list of data with pages.

If you’d like to retrieve a translated string without displaying it, you can use the following syntax:

{% paginate topic_list.item_list by 10 %}
  <ul>
    {% for item in paginate.item_list %}
      {{ item.name }}
    {% endfor %}
  </ul>
  {{ paginate | default_pagination }}
{% endpaginate %}

The code above will limit results in topic_list.item_list by 10 and create a paginator at the end of the list if there is more then 10 items available.

forum_item_list

The {% forum_item_list %} template tag returns a dict with data related to topic (article, ticket) list for specific forum or category. The first argument is a forum or a category to select topics. Returns data into variable followed after "as" parameter. Other optional arguments are available:

  • filter_status - status ID
  • filter_type - type ID
  • filter_tag - tag ID
  • order - order mode for the list. Accept these values:
    • "newest" - order by date of creation DESC.
    • "updated" - order by last date of update (new comment, status, etc) DESC.
    • "comments" - order by count of comments DESC.
    • "popular" - order by count of votes DESC.
    • "downvotes" - order by count of negative votes DESC.
    • "upvotes" - order by count of positive votes DESC.
    • "top" - order by vote amount (difference between positive and negative votes) DESC)
    • "categories" - order by category order (useful for articles)
  • user_filter - uses to filter by specific type related to the specific user. Accepts following values:
    • "tickets" - all tickets related to the user.
    • "topics" - all topics related to the user.
    • "voted_topics" - all topics user voted for.

Returns dict of:

  • item_list - list of selected items (articles, topics or tickets)
  • ... other parameters required to build filters for the list

Example:

{% forum_item_list forum order="updated" as topic_list %}

{% for topic in topic_list.item_list %}
    Topic header: {{ topic.header }}
{% endfor %} 

comment_list

The {% comment_list %} template tag returns a dict with data related to comment's list for specific topic, article or ticket. The first argument is a topic, an article or a ticket. Returns data into variable followed after "as" parameter. Other optional arguments are available:

  • order - order mode for the list. Accept these values:
    • "newest" - order by date of creation DESC.
    • "oldest" - order by date of creation ASC.

Returns dict of:

  • item_list - list of selected items (comments)
  • ... other parameters required to build filters for the list
{% comment_list object order=order as comments %}

user_list

The {% user_list %} template tag returns a dict with data related to user's list. Returns data into variable followed after "as" parameter. Other optional arguments are available:

  • support_agents_only - returns only support agents if True.
  • users_only - returns only users (exclude support agents) if True.
  • filter_language - returns users who has the same language selected as on the current page if True.
  • limit - Integer limit of results.
  • order - order mode for the list. Accept these values:
    • "newest" - order by date of profile creader DESC.
    • "top_commenters" - order by count of comments in community DESC.
    • "name" - order by name.
    • "top_rating" - order by rating DESC.

Returns dict of:

  • item_list - list of selected users
  • ... other parameters required to build filters for the list

Example:

{% user_list order="newest" limit=10 as user_list %}

{% for user in user_list.item_list %}
    User: {{ user.display_name }}
{% endfor %} 

url

The {% url %} template tag returns specific URL. The first argument is the URL name and may accept following values:

  • login_page.
  • new_ticket. Optionally accepts helpdesk forum as a second argument.
  • new_topic. Optionally accepts a community forum or category as a second argument.
  • category_list. Requires a community or a knowledge base forum or category as a second argument.
  • article_list. Requires a knowledge base forum or category as a second argument.
  • topic_list. Requires a community forum or category as a second argument.
  • community_home.

Feel free to contact us if you need a new link available via tag.

Example:

{% url "article_list" forum %}

link

The {% link %} template tag returns an HTML link code for specific URL. It calls portal_url template tag and renders specific HTML code for URL returned. Accepts all the same parameters as portal_url plus additional keyword parameters:

  • label - text on the link
  • target - target parameter for the link

Example:

{% link "article_list" forum label="Open article list" target="_blank" %}

avatar

The {% avatar %} template tag returns an HTML code for user's avatar. Accepts user as a first parameter. Also has additional optional parameter:

  • size - size of avatar in pixels (integer)
  • alt - alt parameneter for img code (text)

Example 1:

{% avatar user %}

Example 2:

{% avatar user size=64 alt="Avatar alt text" %}

user_link

The {% user_link %} template tag returns an HTML code with user's name and link to his profile (in the future when public profile will be available). Accepts user as a first parameter. Also has additional optional parameter:

  • target - where open the link ("_self" or "_blank")

Example:

{% user_link user %}

image

The {% image %} template tag returns an HTML code with image for object. You can use the tag to render images for categories, forums, topic types, etc. It will render code with either image or font awesome icon depend on what you've selected for the object in the project settings. Accepts object as a first parameter. Also has additional optional parameters:

  • width- image width.
  • height - image height.
  • add_class - CSS class to add to the image
  • icon_type - Type of iconf for font awesome icons ("default" or "circle")
  • alt - alt text for the image HTML tag

Example:

{% image topic.type.image height=18 %}

language_selector

The {% language_selector %} template tag generates HTML for user to select portal interface language.

Example:

    {% language_selector %}

    user_or_signin

    The {% user_or_signin %} template tag generates HTML for user to show his avatar and menu or "sign in" label if user is not authenticated. Has an optional parameter:

    • avatar_size - size of avatar in pixels (integer).

    Example:

      {% user_or_signin %}

      search_form

      The {% search_forms %} template tag generates HTML to show search field for portal content. Has an optional parameter:

      • forum - forum where to perform the search. If not provided we do search in all available forums.
      • placeholder - placeholder text for the field.


      Example:

        {% search_form placeholder="Search here..." %}

        navigation

        The {% navigation %} template tag generates HTML to show navigation bar for your portal. Has an optional parameter:

        • add_icons - adds icons next to each menu item.

        Example:

          {% navigation add_icons=True %}

          new_topic_form

          The {% new_topic_form %} template tag generates HTML to show form for new topic.

          Example:

            {% new_topic_form %}

            new_ticket_form

            The {% new_ticket_form %} template tag generates HTML to show form for new ticket.

            Example:

              {% new_ticket_form %}

              new_comment_form

              The {% new_comment_form %} template tag generates HTML to show form for new comment.

              Example:

                {% new_comment_form %}

                forum_item_list_filters

                The {% forum_item_list_filters %} template tag generates HTML to show filters for list of topics, articles or tickets (type filter, status filter, tag filter, order, etc.). As input data accepts result of forum_item_list tag.

                Example:

                  {% forum_item_list forum order="updated" as item_list %}
                  
                  {% forum_item_list_filters item_list %}

                  comment_filters

                  comment_filters

                  The {% comment_filters %} template tag generates HTML to show filters for list of comments (order, etc.). As input data accepts result of comment_list tags.

                  Example:

                    {% comment_list forum order="updated" as item_list %}
                    
                    {% comment_filters item_list %}

                    breadcrumbs

                    breadcrumbs

                    The {% breadcrumbs %} template tag generates HTML to show breadcrumbs for current page of your portal. Has an optional parameters:

                    • add_last - show or hide last item in breadcrumbs.
                    • add_home - show or hide first item (home) in breadcrumbs.

                    Example:

                      {% breadcrumbs add_last=False %}

                      topic_voting

                      The {% topic_voting %} template tag generates HTML to show voter for a topic. Requires a topic as a first argument. Has an optional parameter:

                      • template - name of template to use to generate the voter. You can use your custom template.

                      Examples:

                        {% topic_voting topic %}
                        {% topic_voting topic template="my_custom_voter" %}

                        article_voting

                        The {% article_voting %} template tag generates HTML to show voter for an article. Requires an article as a first argument.

                        Example:

                          {% article_voting article %}

                          follow_button

                          The {% follow_button %} template tag generates HTML to show follow button for an object. Requires an object as a first argument. The object can be one of the following: topic, article, ticket, forum, category.

                          Examples:

                            {% follow_button forum %}
                            {% follow_button topic %}

                            comment_voting

                            The {% comment_voting %} template tag generates HTML to show voter for a comment. Requires a comment as a first argument.

                            Example:

                              {% comment_voting comment %}

                              comment_actions

                              comment_actions

                              The {% comment_actions %} template tag generates HTML to show a comment actions (reply, edit, etc). Requires a comment as a first argument.

                              Example:

                                {% comment_actions comment %}

                                login_panel

                                The {% login_panel %} template tag generates HTML to show login panel page depends on project settings (login/password, social sign in buttons, SSO, remind password link, registration link, etc).

                                Example:

                                  {% login_panel %}

                                  password_reset_form

                                  The {% password_reset_form %} template tag generates HTML to show password reset form.

                                  Example:

                                    {% password_reset_form %}



                                    user_signup_form

                                    The {% user_signup_form %} template tag generates HTML to show Sign Up form.

                                    Example:

                                      {% user_signup_form %}

                                      login_openid_form

                                      The {% login_openid_form %} template tag generates HTML to show Login via OpenId form (the form that user sees when click OpenId sign in button in login panel).

                                      Example:

                                        {% login_openid_form %}

                                        user_settings_form

                                        The {% user_settings_form %} template tag generates HTML to show user's profile settings form for current user.

                                        Example:

                                          {% user_settings_form %}

                                          user_password_change_form

                                          The {% user_password_change_form %} template tag generates HTML to show password change form for current user.

                                          Example:

                                            {% user_password_change_form %}

                                            user_notifications

                                            The {% user_notifications %} template tag generates HTML to show user's notification settings for current user.

                                            Example:

                                              {% user_notifications %}

                                              related_articles

                                              The {% related_articles %} template tag generates HTML to show articles related to provided article. Requires an article as a first argument. Has an optional parameter:

                                              • limit - limit count of related articles (1-10, default 5)

                                              Examples:

                                                {% related_articles article %}
                                                {% related_articles article limit=10 %}

                                                item_prev_and_next_links

                                                The {% item_prev_and_next_links %} template tag generates HTML to show links to previous and next items if exists. Created specially for knowledge base to show previous and next articles but also can be user to show previous and next topics and tickets. Requires an article (topic, ticket) as a first argument. Show links only if they exist. For example, if this is a first item the link to previous will not be shown.

                                                Example:

                                                  {% item_prev_and_next_links article %}

                                                  share_buttons

                                                  The {% share_buttons %} template tag generates HTML to show share in social networks buttons for a page. Usually used on topics and articles pages.

                                                  Example:

                                                    {% share_buttons %}

                                                    satisfaction_survey

                                                    The {% satisfaction_survey %} template tag generates HTML to show satisfaction survey for current topic (or ticket) to author. If user is a support agent and not an author of the topic (or ticket) the tag shows satisfaction survey results for current topic (or ticket).

                                                    Example:

                                                      {% satisfaction_survey %}

                                                      user_page_menu

                                                      The {% user_page_menu %} template tag generates HTML to show user's profile page menu (side menu like settings, topics, tickets, etc). The menu generates depends on current user and project settings.

                                                      Example:

                                                        {% user_page_menu %}

                                                        forum_selector

                                                        The {% forum_selector %} template tag returns an object that contains information to show forum selector and selected forum as well. This is helpful tag if you have more than one Helpdesk or Community forum because the list shows only one forum on time. So, you can let the user to change the forum displayed. Requires a forum list as a first argument. Has an optional parameter:

                                                        • view_type - type of element (selector) rendered in html parameter. Can be "select" (default) or "dropdown_button"

                                                        Returns object with attributes:

                                                        • selected - forum (from the list) selected on current page
                                                        • item_count - count of forums in the list
                                                        • item_list - list of forums
                                                        • html - html code to add selector

                                                        Example:

                                                          {% forum_selector forums as forum_selector %}
                                                          
                                                          {{ forum_selector.html }}
                                                          
                                                          {% topic_list forum_selector.selected order="newest" user_filter=portal.section as list_items %}
                                                          {% for item in list_items.item_list|limit:10 %}
                                                              Topic: {{ item.name }}
                                                          {% endfor %}
                                                          


                                                          date_format

                                                          The filter returns a string representation of the datetime in specific format

                                                          Parameter "format" can consists of these values:


                                                          Format characterDescriptionExample output
                                                          Day
                                                          dDay of the month, 2 digits with leading zeros.'01' to '31'
                                                          jDay of the month without leading zeros.'1' to '31'
                                                          DDay of the week, textual, 3 letters.'Fri'
                                                          lDay of the week, textual, long.'Friday'
                                                          SEnglish ordinal suffix for day of the month, 2 characters.'st', 'nd', 'rd' or 'th'
                                                          wDay of the week, digits without leading zeros.'0' (Sunday) to '6' (Saturday)
                                                          zDay of the year.1 to 366
                                                          Week
                                                          WISO-8601 week number of year, with weeks starting on Monday.1, 53
                                                          Month
                                                          mMonth, 2 digits with leading zeros.'01' to '12'
                                                          nMonth without leading zeros.'1' to '12'
                                                          MMonth, textual, 3 letters.'Jan'
                                                          bMonth, textual, 3 letters, lowercase.'jan'
                                                          EMonth, locale specific alternative representation usually used for long date representation.'listopada' (for Polish locale, as opposed to 'Listopad')
                                                          FMonth, textual, long.'January'
                                                          NMonth abbreviation in Associated Press style. Proprietary extension.'Jan.', 'Feb.', 'March', 'May'
                                                          tNumber of days in the given month.28 to 31
                                                          Year
                                                          yYear, 2 digits with leading zeros.'00' to '99'
                                                          YYear, 4 digits with leading zeros.'0001', …, '1999', …, '9999'
                                                          LBoolean for whether it’s a leap year.True or False
                                                          oISO-8601 week-numbering year, corresponding to the ISO-8601 week number (W) which uses leap weeks. See Y for the more common year format.'1999'
                                                          Time
                                                          gHour, 12-hour format without leading zeros.'1' to '12'
                                                          GHour, 24-hour format without leading zeros.'0' to '23'
                                                          hHour, 12-hour format.'01' to '12'
                                                          HHour, 24-hour format.'00' to '23'
                                                          iMinutes.'00' to '59'
                                                          sSeconds, 2 digits with leading zeros.'00' to '59'
                                                          uMicroseconds.000000 to 999999
                                                          a'a.m.' or 'p.m.' (Note that this is slightly different than PHP’s output, because this includes periods to match Associated Press style.)'a.m.'
                                                          A'AM' or 'PM'.'AM'
                                                          fTime, in 12-hour hours and minutes, with minutes left off if they’re zero. Proprietary extension.'1', '1:30'
                                                          PTime, in 12-hour hours, minutes and ‘a.m.’/’p.m.’, with minutes left off if they’re zero and the special-case strings ‘midnight’ and ‘noon’ if appropriate. Proprietary extension.'1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.'
                                                          Timezone
                                                          eTimezone name. Could be in any format, or might return an empty string, depending on the datetime.'', 'GMT', '-500', 'US/Eastern', etc.
                                                          IDaylight saving time, whether it’s in effect or not.'1' or '0'
                                                          ODifference to Greenwich time in hours.'+0200'
                                                          TTime zone of this machine.'EST', 'MDT'
                                                          ZTime zone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.-43200 to 43200
                                                          Date/Time
                                                          cISO 8601 format. (Note: unlike other formatters, such as “Z”, “O” or “r”, the “c” formatter will not add timezone offset if value is a naive datetime (see datetime.tzinfo).2008-01-02T10:30:00.000123+02:00, or 2008-01-02T10:30:00.000123 if the datetime is naive
                                                          rRFC 5322 formatted date.'Thu, 21 Dec 2000 16:01:07 +0200'
                                                          USeconds since the Unix Epoch (January 1 1970 00:00:00 UTC).

                                                          Example:

                                                            {{ article.created_on|date_format:"Y.m.d" }}
                                                            

                                                            powered_by_userecho

                                                            The {% powered_by_userecho %} template tag generates HTML to add "Powered by UserEcho" to your page. This tag is required to use if you do not have white-label option in your service plan!

                                                            Example:

                                                              {% powered_by_userecho %}

                                                              set_meta

                                                              The {% set_meta %} template tag helps you to set some META variables that we use to generate your page or even you can use in templates "above". For now we only use this parameter:

                                                              • body_class - html classses to be add to <BODY> html tag.

                                                              Example:

                                                              {% set_meta body_class="my-body-class" %}



                                                              Эта статья была полезна для 10 людей. Эта статья помогла вам?