I am new to twig
and struggling with the following scenario.
I have a select
for country names (United Kingdom & Republic of Ireland) and I'm struggling when the twig
variable value returned does not match a value in the select
.
I have it working if the variable is empty but need help with the above.#
This is my full select
HTML (I have removed all the twig
code to make it clear)
<select id="compAddCountryDd" name="compAddCountryDd" >
<option value='' >Please Select</option>
<option value="United Kingdom">United Kingdom</option>
<option value="Republic of Ireland">Republic of Ireland</option>
</select>
This is the code I have for my 'Please Select' option
if empty, which I have working
{% if companyDetails is defined and companyDetails.address.country == '' %}
<option value=''
selected style="display: none" disabled>
Please Select
</option>
{% endif %}
But I cant seem to get it to display if the variable is defined
but does not match the values in the select
.
This I have tried the following code for the twig
if
{% if companyDetails is defined and companyDetails.address.country == '' and
companyDetails.address.country != 'United Kingdom' and
companyDetails.address.country != 'Republic of Ireland' %}
and also
{% if companyDetails is defined and companyDetails.address.country == '' or
companyDetails.address.country != 'United Kingdom' or
companyDetails.address.country != 'Republic of Ireland' %}
Basically, I need my 'Please Select' option
to be displayed if it:
- Is defined
- Does not equal 'United Kingdom'
- Does not equal 'Republic of Ireland'
CodePudding user response:
You are missing some parentheses here to comply to your logic:
- You want to the variable to be defined
- AND
- The country is either empty OR not equal to the UK AND not equal to Ireland
{% if companyDetails|default and (companyDetails.address.country|trim == '' or companyDetails.address.country != 'United Kingdom' and companyDetails.address.country != 'Republic of Ireland') %}
Show
{% else %}
Don't show
{% endif %}
I would however rewrite this to the following:
{% if companyDetails|default and (companyDetails.address.country|trim == '' or companyDetails.address.country not in [ 'United Kingdom', 'Republic of Ireland' ]) %}
Show
{% else %}
Don't show
{% endif %}