mozilla / nunjucks

A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)
https://mozilla.github.io/nunjucks/
BSD 2-Clause "Simplified" License
8.48k stars 634 forks source link

Calling many functions without comments #1448

Closed szepeviktor closed 8 months ago

szepeviktor commented 9 months ago

Hello! I see 30 lines of function calls with ever-opening/closing comments. https://github.com/conedevelopment/cone-site/blob/main/src/_includes/partial/meta.html#L1-L30

How is it possible to write blocks of Nunjucks code without comment signs on each line?

webketje commented 8 months ago

It is not possible to have "multiline code block execution" in Nunjucks. In the example you linked to, it's possible to condense

{% if page.url.length > 1 %}
    {% set pageTitle = title + ' - ' + site.name %}
{% else %}
    {% set pageTitle = site.name %}
{% endif %}
{% if metaTitle %}
    {% set pageTitle = metaTitle %}
{% endif %}

into:

{% set pageTitle = metaTitle ? metaTitle : (page.url.length > 1 ? (title + ' - ' + site.name) : site.name) %}

If you don't like to have too much logic in your Nunjucks templates, you can choose to encapsulate this logic in a {% macro %}, eg:

{% macro pageTitle(title, isIndex, siteTitle) %}
{% if isIndex and title %}
  {{ title | safe }} - {{ siteTitle | safe }}
{% elif title %}
  {{ title | safe }}
{% elif siteTitle %}
  {{ siteTitle | safe }}
{% endif %}
{% endmacro %}

{# usage:  {{ pageTitle(title, page.url.length > 1, site.name) }} #}
szepeviktor commented 8 months ago

Thank you very much @webketje!

🐴 This is not the horse I will ride. Cc @adamlaki