Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do a preg_replace in 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?

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

Ex.

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

output: http://website.com/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).

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).


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.

Thank you ahead of time for the help!

like image 948
Tanya H Avatar asked Jul 10 '13 14:07

Tanya H


1 Answers

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

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

like image 143
Alexey B. Avatar answered Jan 03 '23 12:01

Alexey B.