我想检查一个变量中是否包含多个字符串值,到目前为止,我知道我可以检查一个变量中的单个字符串值包含条件,但是在多个值包含上都找不到任何内容。
有人可以帮我吗?
我现在拥有的是:
{% if "VenuesController::detailsAction" not in controllerAndActionName %}
我想做什么:
{% if ["VenuesController::detailsAction", "VmsController::indexAction", "DefaultController::headerAction"] not in controllerAndActionName %}
这可能吗?
答案 0 :(得分:2)
使用自定义的Twig扩展名,我可以通过以下方式实现:
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('checkMultipleStringValuesContainment', array($this, 'checkMultipleStringValuesContainment'))
);
}
public function checkMultipleStringValuesContainment($values, $variable) {
$joinedValues = join($values, "|");
if (preg_match('~('.$joinedValues.')~', $variable)) {
return true;
} else {
return false;
}
}
然后再次:
{% if checkMultipleStringValuesContainment(["VenuesController::detailsAction", "StaticController::howitworksAction", "StaticController::listyourvenueAction"], controllerAndActionName) == false %}
答案 1 :(得分:1)
您需要使用<string> not in <array>
而不是<array> not in <string>
:
{% if controllerAndActionName not in ["VenuesController::detailsAction", "VmsController::indexAction", "DefaultController::headerAction"] %}
答案 2 :(得分:1)
不知道您是否可以直接在twig
中进行此操作,但是应该采用这种解决方法
{% set bool = true %}
{% for string in ["VenuesController::detailsAction", "VmsController::indexAction", "DefaultController::headerAction"] %}
{% if string in controllerAndActionName %}
{% set bool = false %}
{% endif %}
{% endfor %}
{% if bool %}
Foo
{% endif %}