Twig check multiple values - php

I have about 5 or so tables that are booleans. I want to test all of them and if one or more return true then to do something.
So far I have tried something like
{% if product.is_red == true %}
<h1>Has colors</h1>
{% elseif product.is_yellow == true %}
<h1>Has colors</h1>
{% elseif product.is_green == true %}
<h1>Has colors</h1>
{% elseif product.is_purple == true %}
<h1>Has colors</h1>
{% elseif product.is_black == true %}
{% endif %}
But if anyone of them returns true then it will say
Has Colors
whatever the amount of times it returns true. Is there any way to check all of them and if one more returns true then returns "Has colors"?

You have to work with a flag in twig to keep track if one or more colors are specified. A shorter example of the code would be (should also work with an object product):
{%
set product = {
'is_red' : false,
'is_yellow' : false,
'is_blue' : true,
'is_green' : false,
}
%}
{% set has_color = false %}
{% for color in ['red', 'yellow', 'blue', 'green', 'purple', ] %}
{% if product['is_'~color] is defined and product['is_'~color] %}{% set has_color = true %}{% endif %}
{% endfor %}
{% if has_color %}
<h1>Has color</h1>
{% endif %}
fiddle

Related

BoltCMS fetch content filters by taxonomies

trying to achieve needed behaviour with Bolt CMS content types, but can't, so asking for help
Have Content Type and 2 taxonomies, industries_t and services_t
{% set condition = condition|merge({'industries_t' : industriesFilter|join(' || ')}) %}
{% endif %}
{% if topicsFilter is not empty %}
{% set condition = condition|merge({'services_t' : topicsFilter|join(' || ')}) %}
{% endif %}
{% if app.request.query.get('from') is not empty or app.request.query.get('to') is not empty %}
{% set fromFilter = app.request.query.get('from') is not empty ? app.request.query.get('from') : '2014-01-01' %}
{% set toFilter = app.request.query.get('to') is not empty ? app.request.query.get('to') : 'now'|date('Y-m-d') %}
{% set condition = condition|merge({'publishedAt' : '\>' \~ fromFilter \~ ' && \<' \~ toFilter }) %}
{% endif %}
{% if app.request.query.get('search') is not empty %}
{% set condition = condition|merge({'title' : '%' \~ app.request.query.get('search') \~ '%' }) %}
{% endif %}
{% setcontent casestudies = 'case-studies' where condition orderby "-publishedAt" limit 6 %}
I need to fetch records, that has ´"industries_t" = "Test" OR services_t = "Another"´
right now, it works like "SELECT records where industries_t = "Test" and services_t = "Another"
is there any way to make it "SELECT records where industries_t = "Test" OR services_t = "Another"?

Twig parse array and check by key

I'm trying to see if an array has a key. The first case returns 2 results 1-5 and , while the second seems to work fine.
Any ideea why is this happening ?
{% set options = {'1' : '1' , '1-5' : '5' , '1-12' : '12' } %}
{% set selected = '1-5' %}
Wrong check
{% for k,v in options %}
{% if k == selected %}
{{ k }}
{% endif %}
{% endfor %}
Right
{% for k,v in options %}
{% if k|format == selected|format %}
{{ k }}
{% endif %}
{% endfor %}
https://twigfiddle.com/c6m0h4
Twig will compile the "wrong check" in the following PHP snippet:
if (($context["k"] == (isset($context["selected"]) || array_key_exists("selected", $context) ? $context["selected"] : (function () { throw new RuntimeError('Variable "selected" does not exist.', 6, $this->source); })()))) {
Simplified this becomes
if ($context["k"] == $context["selected"])
Because the type of context["k"] (for the first iteration) is an integer, PHP will typecast the right hand part of the equation to an integer as well. So the equation actually becomes the following:
if ((int)1 == (int)'1-5')
and casting 1-5 to an integer becomes 1, making the final equation to:
1 == 1 which evaluates to true
You can test the fact that first key gets treated as integer with the following PHPsnippet by the way
<?php
$foo = [ '1' => 'bar', ];
$bar = '1-5';
foreach($foo as $key => $value) {
var_dump($key); ## output: (int) 1
var_dump($key == $bar); ## output: true
}
demo

How would you do ternary conditionals inside {%%} in Twig

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 %}
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 %}

Is identical (===) in Twig

Here's the PHP code:
if ($var===0) {do something}
It "does something" only when $var is actually 0 (and if $var is not set, it doesn't work, so everything is OK).
However, Twig doesn't support === operator, and if I write:
{% if var==0 %}do something{% endif %}
it "does something" all the time (even when $var is not set). In order to fix it, I wrote such a code:
{% if var matches 0 %}do something{% endif %}
Is it a proper way to do === comparison in Twig, or I did something wrong here? If it's wrong, how should it be fixed?
You need to use same as in Twig for === comparisons:
{% set var1=0 %}
{% set var2='0' %}
{% if var1 is same as( 0 ) %}
var1 is 0.
{% else %}
var1 is not zero.
{% endif %}
{% if var2 is same as( 0 ) %}
var2 is 0.
{% else %}
var2 is not 0.
{% endif %}
{% if var2 is same as( '0' ) %}
var2 is '0'.
{% else %}
var2 is not '0'.
{% endif %}
Here is a twigfiddle showing it in operation:
https://twigfiddle.com/k09myb
Here is the documentation for same as also stating that it is equivalent to ===. Hope that helps you!
Twig doesn't have === but it has same as instead. See: https://twig.sensiolabs.org/doc/2.x/tests/sameas.html
So you could write:
{% if var is same as(0) %}do something{% endif %}
Eventually, you can use is defined to check whether the variable is set.

Merge key and value into an array in Twig file

I want to add key and value into array in twig file. But I am facing following issue "Twig_Error_Syntax: A hash key must be a quoted string or a number"
{% set phoneCount = 0 %}
{% set phoneNumbers = {} %}
{% for currPhone in currBroker.phones %}
{% if (currPhone.type == 'Work' or currPhone.type == 'Mobile') and phoneCount <= 2 and currPhone.number !='' %}
{% set phoneCount = phoneCount + 1 %}
{% set phoneNumbers = phoneNumbers|merge({ currPhone.type:currPhone.type }) %}
{% endif %}
{% endfor %}
{{ phoneNumbers|print_r }}
I just need the syntax of merging key and value into array.
I tried by giving static inputs and its works
{% set phoneNumbers = phoneNumbers|merge({ 'work':'(011)112-1233' }) %}
But its not working for dynmic input. Please help!!
You have to wrap your key in braces :
{% set phoneNumbers = phoneNumbers|merge({ (currPhone.type) : currPhone.type }) %}
Tested and working example :
{% set currPhone = {type: 'test'} %}
{% set phoneNumbers = {} %}
{% set phoneNumbers = phoneNumbers|merge({ (currPhone.type) : currPhone.type }) %}
{% dump(phoneNumbers) %}
I get :
array:1 [▼
"test" => "test"
]

Categories