How would you do ternary conditionals inside {%%}

2019-05-23 21:46发布

问题:

I want to render parameters if they exist but can't find a way of correctly displaying it and keep getting An opened parenthesis is not properly closed. Unexpected token "punctuation" of value ":" ("punctuation" expected with value ")")

where

{% setcontent records = 'properties' where
{filter:search_term,
((classification) ? ('classification':classification):(''))
} printquery  %}

回答1:

To use it inside Bolt CMS, first define your options and then pass that to Bolt CMS

{% set options = { filter: search_term , } %}
{% if classification is defined and classification|trim != '' %}
    {% set options = options|merge({classification:classification,}) %}
{% endif %}

{% setcontent records = 'properties' where options printquery  %}

After rereading your question you are probably looking for something like this,

{% set records %}
'properties' where { 
    filter : '{{ search_term }}',
    classification: '{{ classification is defined ? classification : '' }}',
} printquery  %}
{% endset %}

{{ records }}

However using the filter default here is more suited than using the ternary operator,

{% set records %}
'properties' where { 
    filter : '{{ search_term }}',
    classification: '{{ classification|default('') }}',
} printquery  %}
{% endset %}

{{ records }}

demo


To omit properties you would use the following,

{% set records %}
'properties' where { 
    filter : '{{ search_term }}',
    {% if classification is defined and classification|trim != '' %}classification: '{{ classification }}',{% endif %}
} printquery  %}
{% endset %}