how to do a preg_replace in twig - symfony

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!

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.

Someone seems to have created a Twig Extension for preg_replace, see https://github.com/victor-in/Craft-TwigPCRE

You can do it like that. It's a bit ugly but it works.
uri|split('base_path')|join('')

Related

2sxc List.Presentation in General View

I have an entity type "Post" and I would like to create a view that will show one random Post with a given category. I created a Data pipeline that grabs all posts and I created a view with ListPresentation = a "TemplateSettings" entity type that lets me choose categories.
I planned to use the Razor template to filter the items for those matching the categories in List.Presentation.Categories. But, I can't seem to reference List.Presentation.Categories. I get an error that System.Collections.Generic.List doesn't contain an entry for "Presentation". When I use #ListPresentation, the whole object in null... so #ListPresentation.Toolbar, etc. all throw errors, despite me having set a "Demo Item".
Can anybody see what would be wrong with this setup? How do I reference List Presentation stuff in Razor?
Thanks.
I figured this out... The direct thing seems to be "ListPresentation", but the snippets use "List.Presentation". Still, it wasn't working in my case because I was using a data query that didn't include the module data. So, I had to modify that query to include the module data as well as the full list of entities, regardless of the module. Then, I got the full list from one data stream, and the ListPresentation fields were available.
Note also that you can use ListContent.Presentation - that would be the newest, most consistent API which always places Presentation information as a property of the entity it's describing.

Symfony2 pass whole entity object to path()

Why I need this?
When I want to change the route from /news/{slug} to /news/{id} for example, I need to replace all places where path('news', {'slug': 'my-post'} is called. I want to pass the entity like so path('news', {'post': post}) and then change the route however I like. This will give me the flexibility to easily change the routes. Thanks.
You cannot pass eneity as param. path function takes only string and number arguments, because this function generate url based on routing.
How do you imagine passing object to browser url bar?
/news/"{object": std_what_the_#?}
Of course you can make your own twig function and pass object to make your url.
This way you can check your object has slug property and choose your route and params. Anyway you have to do it myself.
I hope it help but your question is not clear...

Symfony 2: Deserialize object in twig

I'm a newbie and this is my first question so please be nice with me :)
In my Symfony 2 project I want to pass an $user object from my controller to the twig template. This object contains all relevant Information (like username, activepage ...) for rendering the view. My problem is that I would also like to put the result of mysqli database query inside the object. To be able to retrieve it in my twig template, I need two serialize the result object(array?) in the controller before passing. Unfortunately I dont know a way how to deserialize that object in twig( no twig filter available).
My questions:
Is this actually an elegant way or should i rather pass all objects in an array to the template?
Would it work to write a deserialize function inside the user class, which i can call in the twig template?
Will performance be ok?
How do the experienced people do this?
Thx for helping!
Built an array with your data in your controller and render it like this to your template :
return $this->render('yourbundle:example:index.html.twig', array(
'myArray' => $array,
Then in your template you have access to myArray like this :
{% for data in myArray %}
...
{% endfor %}
I made a service such a parameter bag which I can add parameters/values along the process, and render every parameters with twig so I can use them in javascript.
For that I had to use mostly JsonSerializable php interface (PHP 5.4+), and json_decode twig filter.
I think it is a nice way to pass variables to js like this because you can use this service when building your project.

symfony2 render action array to more than 1 template

I am new to Symfony (and PHP as well). I currently have a method indexAction in my Controller which renders an array of objects ($results) to the index view (index.html.twig template) - this part works.
I would like to use the SAME array that I am rendering in index.html.twig in a different view page. Is it possible to render an array to multiple templates?
I've tried adding a 2nd render statement, but it doesn't work (I get an error saying that the array being called in the 2nd template does not exist - thus only the 1st render statement is working). I've thought about copying and pasting the content of indexAction into get_stuffAction (both methods in the same controller), but I think this is probably not the best way to proceed (lots of redundant code).
return $this->render('TryBundle:Try:index.html.twig', array('results'=>$results));
return $this->render('TryBundle:Try:get_stuff.html.twig', array('results'=>$results));
Just wondering if someone knows how to render an array to multiple views, or if I can somehow use the array created in indexAction function in the get_stuffAction function.
Thank you kindly for your time!
why don't you create a method in your controller to get the result, then in each action just call that method for the data you want.

Symfony2: Why weren't query string parameters included in the routing component?

I am porting a legacy application to Symfony2 and I am struggling because routing doesn't include query string parameters. Some quick examples: Suppose you have a search page for books where you can filter results based on criteria:
http://www.bookstore.com/books?author=Stephen+King&maxPrice=20
The nice thing about query string parameters in a case like this is you can have any number of filters, use the ones you want for any given request, and not crowd the URL with filters you're not using.
Let's say we rewrote the routing for the above query using the Symfony2 routing component. It might look like this:
http://www.mybookstore.com/book/any_title/stephen%20king/any_release_date/max_price_20/any_min_price/any_format/any_category
Even not taking into account how arbitrarily long an unclean that URL is I still don't think it is as intuitive because each 'segment' of that route is not a key value pair but instead just a value (e.g. author=Stephen+King > /stephen%20king/).
You can of course access query string parameters in the controller by passing the Request object into the action method (e.g. indexAction(Request $request) {) but then validating them and passing them into other parts of the application becomes a hassle (i.e. where I find myself now). What if you are using the Knp Menu Bundle to build your sidebar and you want parts to be marked as .current based on query string parameters? There is no functionality for that, just functionality to integrate with Symfony2 routes.
And how to validate that your query string parameters are acceptable? I am currently looking at validating them like a form to then pass them into the database to generate a query. Maybe this is the way the Symfony2 team envisioned handling them? If so I'd just really like to know why. It feels like I'm fighting the application.
I ended up actually asking Fabien this question at Symfony Live San Francisco 2012. There was another talk at the same conference in regards to this question and I will share with you the slides here:
http://www.slideshare.net/Wombert/phpjp-urls-rest#btnNext
Basically in the slides you can see that the author agrees with me in that query string parameters should be used for filtering. What they should not be used for is determining a content source. So a route should point to a product (or whatever) and query string parameters should then be used in your controller to apply whatever logic you require to filter that content source (as per Fabien).
I ended up creating an entity in my application that I bind all my query string parameters to and then manipulate, much the same way forms are handled. In fact when you think about it it's basically the same thing.
Like in Symfony1, query strings are independent from the route parameters.
If you have a path defined as #Route("/page/{id}", name="single_page"), you can create a path in your view like this:
{{ path('single_page', { id: 3, foo: "bar" }) }}
The resulting URL will be /page/3?foo=bar.

Resources