doucongqian6644 2016-04-21 16:52
浏览 64
已采纳

查找数组中的项是否在子字符串twig中

im reading Find substring in the string in TWIG

and on a single item it works fine for me.

<!-- language: lang-html -->
<li {% if 'page' in app.request.get('_route')|lower %}class="active"{% endif %}>
    <a href="{{path('adminPage')}}">
        <i class="fa fa-file-text"></i> <span>{% trans %}pages_text{% endtrans %}</span> <small class="label pull-right bg-{% if nav_options.count_pages > 0 %}primary{% else %}red{% endif %}">{{ nav_options.count_pages }}</small>
    </a>
</li>

now I find myself needing it to happen differently.

how would I do to find if "items in this array" are contained in "this substring"

the example would be something like this

{% if ['str1','str2'] in/contained in app.request.get('_route')|lower %}class="active"{% endif %}

I tried this and does not work.

I also would rather avoid using the "or" operator, if its a requirement so be it, but if it can be avoided, the better.

I even went and attempted a split parameter.

{% if 'page,blog'|split(',') in app.request.get('_route')|lower %}active {% endif %}

no dice!

the code is meant to allow me to have "several possible routes" inside a collapsible menu item, and if any of the possible route names (i have several route names, blog, blogAdd, blogEdit, blogPost etc) contains "blog" (same with page, and many others) the "active" class should be printed.

  • 写回答

2条回答 默认 最新

  • dongyangben6144 2016-04-22 15:22
    关注

    Creating a custom twig function would be an easier solution to use

    $function = new Twig_SimpleFunction('array_in_string', function ($haystacks, $needle) {
        foreach($haystacks as $haystack) if (stripos($haystack, $needle) !== false) return true;
        return false;
    });
    
    $twig = new Twig_Environment($loader);
    $twig->addFunction($function);
    

    Then you call this function in Twig with :

    {% if array_in_string(['page','blog',], app.request.get('_route')) %}
       {# do sthing #}
    {% endif %}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵