如何在树枝中进行 preg_replace [英] how to do a preg_replace in twig

查看:24
本文介绍了如何在树枝中进行 preg_replace的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试使用视图的当前 url 创建一个变量.为了获取 url,我使用了 {% set uri = app.request.uri %} (uri 是我的变量,它是该特定视图的当前 url).问题是,我只对 url 的独特之处感兴趣(它的结尾 - 数组中的唯一对象 - 恰好是一个 uri),而不是开头(我的应用程序的路径).我想我可以使用 preg_replace 来做到这一点,但 TWIG 没有这个功能.只是想知道是否有人会知道如何完成我想要做的事情?

I currently am trying to make a variable using the current url for the view. To get the url, I am using {% set uri = app.request.uri %} (uri being my variable which is the current url for that particular view). The thing is, I am only interested in what makes the url unique (the end of it - a unique object from an array - happens to be a uri), and not the beginning (path to my application). I was thinking I could use a preg_replace to do so, but TWIG doesn't have this function. Just wondering if someone would know how to accomplish what I am trying to do?

我是 Symfony 的新手(并且对 PHP 相当陌生),所以我的解释可能不清楚(抱歉).

I'm new to Symfony (and fairly new to PHP), so my explanations may not be clear (sorry).

例如

{% set uri = app.request.uri %}

输出:http://website.com/http://item.org/1

我想将 uri 变量修改为只有 http://item.org/1(而不是我网站的路径).

I want to modify the uri variable to ONLY have http://item.org/1 (and not the path to my website).

我正在考虑使用 preg_replace 创建一个 Twig Extension 将允许我这样做..但不确定这是否是最好的方法(缺乏经验).

I'm thinking creating a Twig Extension with the preg_replace will allow me to do this ..but not sure if it's the best way to go (inexperienced).

总体目标:视图中uri"的唯一值由具有属性的对象数组($results)中的另一个视图附加到网站路径,其中一个是uri".我的最终目标是只显示 $results 数组中某个对象的所有关联属性(或行).我想我可以通过首先在 foreach 中创建一个键(我的 uri 变量),然后返回数组中与该键匹配的行来做到这一点. 这就是我尝试创建一个变量的原因使用 url,以便我可以将其用作 foreach 循环的键来迭代 $results.我没有使用数据库或 Doctrine.

Overall goal: The unique value for "uri" in the view is appended to the websites path by another view from an array of objects ($results) with attributes, one being "uri". My ultimate goal is to only display all associated attributes (or row) for an object in my $results array. I was thinking I could do this by first creating a key (my uri variable) in a foreach, and returning the row in the array which matches this key. This is why I am trying to create a variable with the url so that I can use it as a key for my foreach loop to iterate over $results. I am NOT using a database or Doctrine.

提前感谢您的帮助!

推荐答案

最好的方法是将逻辑从模板移到控制器.

The best way is to move the logic from template to the controller.

如果您需要在 twig 中使用 preg_replace,您必须创建自定义扩展.

If you need preg_replace in twig you must create custom extension.

这篇关于如何在树枝中进行 preg_replace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆