Closed notakoder closed 1 year ago
trim
removes a set of characters (not a substring! defaults to whitespaces) from the beginning and end of a string. replace
is for replacing a fixed substring by another string. What you're looking for is slice
:
<a href="{{ ("bar" ~ current_page.id|slice(3))|link }}">Page from Bar</a>
I've additionally added Pico's link
filter to create the URL. As some syntactic sugar, you could also use Twig's [start:length]
syntax, even though it's the same as slice(start, length)
:
<a href="{{ ("bar" ~ current_page.id[3:])|link }}">Page from Bar</a>
Thanks. I choose the slice filter. That works.
I think I would continue this thread with another connected problem instead of creating a new issue. Since there are many redirects of the same page, I realise that the HTML select option would suit better than many links on the page. So the idea is to redirect the page as per the option selected from the select menu. I guess this would require taking advantage of the onchange
attribute of select element. Do I need to really need an external function that redirects the page, or can I achieve the redirection in a simpler manner?
Using a <select>
element makes things just way harder - without either JavaScript or a Pico plugin written in PHP you won't be able to implement it. Better use regular <a href="">
elements. With appropriate CSS rules you could even mimic the behaviour of a <select>
element.
Understood. I'll work on it. Thanks by the way.
I am trying to redirect a page to another page with the same file name but in another directory. The directories are three characters long. So my plan is to take the current page id (foo/page), replace the first three characters (foo or whatever) with another specific three characters (bar). So
example.com/foo/page
will becomeexample.com/bar/page
. The problem I face is with the twig syntax. Here is a pseudo code:<a href="{{ base_url }}/{{ current_page.id|trim(3 char from (side="left")| ~ 'bar' }}">Page from Bar</a>
How do I replace the first any 3 characters and add three specific characters instead? The
trim
twig documentation doesn't say anything about targeting first n number of characters or the use of regular expressions. Thereplace
documentation is even more short. Any help will be much appreciated.