我是 Twig 的新手,并且在以下情況下苦苦掙扎。
我有一個select國家名稱(英國和愛爾蘭共和國),當回傳的 Twig 變數值與select.
如果變數為空但需要上述幫助,我可以讓它作業。
這是我的完整selectHTML(我已洗掉所有 Twig 代碼以使其清晰)
<select id="compAddCountryDd" name="compAddCountryDd" class="form-control address">
<option value='' class="optionPlaceholder">Please Select</option>
<option value="United Kingdom">United Kingdom</option>
<option value="Republic of Ireland">Republic of Ireland</option>
</select>

這是我的“請選擇”的代碼(option如果為空),我正在使用
{% if companyDetails is defined and companyDetails.address.country == '' %}
<option value='' class="optionPlaceholder"
selected style="display: none" disabled>
Please Select
</option>
{% endif %}
但如果變數是defined但不匹配select.
我已經為 Twig 嘗試了以下代碼if
{% if companyDetails is defined and companyDetails.address.country == '' and
companyDetails.address.country != 'United Kingdom' and
companyDetails.address.country != 'Republic of Ireland' %}
并且
{% if companyDetails is defined and companyDetails.address.country == '' or
companyDetails.address.country != 'United Kingdom' or
companyDetails.address.country != 'Republic of Ireland' %}
基本上,如果出現以下情況,我需要option顯示“請選擇”:
- 被定義為
- 不等于“英國”
- 不等于“愛爾蘭共和國”
uj5u.com熱心網友回復:
您在此處缺少一些括號以符合您的邏輯:
- 您想要定義的變數
- 和
- 該國家或地區為空或不等于英國且不等于愛爾蘭
{% 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 %}
但是,我會將其重寫為以下內容:
{% 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 %}
演示
uj5u.com熱心網友回復:
這將是創建一個帶有 ChoiceType 的表單類的好機會?更易于在控制器中管理(獲取存盤庫、顯示/不顯示/禁用)、分離代碼和添加翻譯
檔案中的一些很好的例子:https ://symfony.com/doc/current/reference/forms/types/choice.html
另一個很好的例子:https ://symfonycasts.com/screencast/symfony-forms/dynamic-choice-type
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/461389.html
