Lets say that i have the following route annotations for a controller action:
* #Route("/post/{post_id}/", name="post.view")
* #Route("/post/", name="post.current_view")
And I want to use twig to generate the url for this:
{{ url(basePath~'view', {'post_id':post.postId}) }}
//basePath will either be "post." or "post.current_"
What i currently get is:
domain.com/post/1/
domain.com/post/?post_id=1
What i want though is for the second route to be generated ignoring any "EXTRA" parameters passed to it so that i would only get:
domain.com/post/
Does anyone know if this is something that can be natively accomplished? I know i could right a custom twig function that uses the router and then i can generate the routes and strip the query string but i want to avoid that if there is an easy toggle somewhere that i have missed.
Solution #1 you could just add an if clause
{% if BasePath == 'post.' %}
{{ url(BasePath~'view', {'post_id':post.postId}) }}
{% elseif BasePath == 'post.current_' %}
{{ url(BasePath~'view') }}
{% endif %}
maybe not the most elegant but should work.
Solution #2
spliting url with question marks and getting the first string
{% set myUrl = url(basePath~'view', {'post_id':post.postId}) %}
{{ myUrl|split("?")|first }}
Solution #3 Or you can override the url function by extending RoutingExtension class of twig.
Symfony\Bridge\Twig\Extension\RoutingExtension
can find an example here with path but url should be the same.
You should override this function
public function getUrl($name, $parameters = array(), $schemeRelative = false)
{
return $this->generator->generate($name, $parameters, $schemeRelative ? UrlGeneratorInterface::NETWORK_PATH : UrlGeneratorInterface::ABSOLUTE_URL);
}
your function could look like this:
public function getUrl($name, $parameters = array(), $schemeRelative = false)
{
$yourUrl = parent::getUrl($name, $parameters = array(), $schemeRelative = false);
return strstr($yourUrl, '?' , true);
}
what id oes it removes everything afther the question mark.
To override the default class you have to add to the parameters
twig.extension.routing.class: MyNamespace\MyRoutingExtension
I guess not, you need a preg_replace filter and this isn't natively defined
Related
Ive been using Wordpress for more than a year now. But I was stuck with the implementation of Timber twig framework get the current URL. I tried these codes below codes but no luck,.
{{ site.url.current }}
{{ app.request.getRequestUri() }}
Twig templates engine: get current url
Have you tried:
URLHelper::get_current_url()
Doc: https://timber.github.io/docs/reference/timber-urlhelper/#get_current_url
So, you should be able to feed this as a variable into your template.
Or if you want to get a step further and extend Timber's Twig i.e. creating a filter or function like:
$twig->addFilter(new \Twig_SimpleFilter('is_current_url', function ($link) {
return (URLHelper::get_current_url() == $link) ? true : false;
}));
Which should bring things down to:
{{ 'http://example.org/2015/08/my-blog-post' | is_current_url }}
BTW: Internally, get_current_url() returns: $_SERVER['HTTP_HOST']/$_SERVER['SERVER_NAME'] + $_SERVER["REQUEST_URI"]
Adding ['current_url'] in functions.php under add_to_context function worked for me:
public function add_to_context($context)
{
// $context['foo'] = 'bar';
$context['current_url'] = Timber\URLHelper::get_current_url();
$context['site'] = $this;
return $context;
}
You then will be able to use it globally in your twig templates:
<pre>
Current Url: {{ dump(current_url) }}
</pre>
I have a working Drupal 8 site with the following in THEME.theme:
function THEME_preprocess_node(&$variables) {
$vars['get']['vguid'] = \Drupal\Component\Utility\XSS::filter($_GET['vguid']);
}
If I add the same line to THEME_preprocess_page() I get "Undefined index: in 'THEME_preprocess_page' when I attempt page loads.
In the the twig I have {{ get.vguid }} and have also tried {{ app.request.parameter.get("vguid") }}
In the twigs (after cache is cleared) I get no value when page is accessed like /mobile-video?vguid=15991b1f-2ad2-11e7-8da8-22000aeb1f8b
How do I get a sanitized query string value into my twig?
I did it like this and I had no problems:
function THEME_preprocess_TEMPLATE(&$variables)
{
$variables['query__param'] = XSS::filter($_GET['keys']);
}
In your function you are using $vars and defining $variables as a parameter, maybe you should change that? $vars['get']['vguid'] => $variables['get']['vguid']
{{ app.request.query.get("vguid") }}
I tried dump variables in block template (block_core_children_pages.html.twig) by {{ dump() }} but it turn into blank page. Anybody have same problem? and I have some questions also:
How to pass a variable from function: {{ sonata_page_render_container('footer', 'global' ) }} to template ?
What are variables is passed by default to block template?
Thanksss alot.
The sonata_page_render_container function takes the following arguments:
public function renderContainer($name, $page = null, array $options = array())
So you have the third argument to specify some options/settings to add to your block, like this:
{{ sonata_page_render_container('footer', 'global', {mysetting: myvalue}) }}
After that, you can modify your execute() BlockService's method to use the settings you passed.
I'm sharing templates between client and server and would like to output the raw template inside a script tag which is possible with verbatim.
http://twig.sensiolabs.org/doc/tags/verbatim.html
However it would be nicer if this could be applied as a filter to the include but it doesn't seem possible?
I'm new to twig so excuse me if i've missed obvious functionality.
I ran into the same problem, and this page came up in my search results. In the time since this question was answered, the Twig developers added this functionality into the library. I figured I should add some details for future searchers.
The functionality to include raw text (aka for client-side templates using the same syntax as Twig) is accomplished with the source function.
Ie: {{ source('path/to/template.html.twig') }}
http://twig.sensiolabs.org/doc/functions/source.html
I was looking for something like this too because I'm using Twig.js for some client-side templating along with Symfony. I was trying to share templates between the server-side and client-side code, so I needed content to be parsed in some cases and treated as verbatim in others, which proved to be a bit tricky.
I couldn't find anything built into Twig to help with this, but luckily, it's pretty easy to extend Twig to get what you're looking for. I implemented it as a function, but you may be able to do it as a filter too.
services.yml
statsidekick.twig.include_as_template_extension:
class: StatSidekick\AnalysisBundle\Twig\IncludeAsTemplateExtension
tags:
- { name: twig.extension }
IncludeAsTemplateExtension.php
<?php
namespace StatSidekick\AnalysisBundle\Twig;
use Twig_Environment;
use Twig_Extension;
class IncludeAsTemplateExtension extends Twig_Extension {
/**
* Returns a list of global functions to add to the existing list.
*
* #return array An array of global functions
*/
public function getFunctions() {
return array(
new \Twig_SimpleFunction( 'include_as_template', array( $this, 'includeAsTemplate' ), array( 'needs_environment' => true, 'is_safe' => array( 'html' ) ) )
);
}
function includeAsTemplate( Twig_Environment $env, $location, $id ) {
$contents = $env->getLoader()->getSource( $location );
return "<script data-template-id=\"{$id}\" type=\"text/x-twig-template\">{$contents}</script>";
}
/**
* Returns the name of the extension.
*
* #return string The extension name
*/
public function getName() {
return 'include_as_template_extension';
}
}
Usage in Twig file
{{ include_as_template( 'Your:Template:here.html.twig', 'template-id' ) }}
If you have a Twig file like this:
<ul class="message-list">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
The output will be this:
<script data-template-id="template-id" type="text/x-twig-template">
<ul class="message-list">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
</script>
The work is derived from Kari Söderholm's answer here. Hope that helps!
Basically, I am looking for the filter equivalent of the attribute() function for objects and arrays. I want to be able to apply a filter, whose name is stored in a variable.
{#
This works and is really useful
prints object.someVar
#}
{% set varName = 'someVar' %}
{{ attribute(object,varName) }}
{#
The function "filter" does not exist
#}
{% set filterName = 'somefilter' %}
{{ filter(object,filterName) }}
To reach this goal you have to extend your TwigFilter.
How to initially write you Extension you can read here.
Assuming that you have created you extension, you have define your function, let's say applyFilter.
//YourTwigFilterExtension.php
public function getFunctions()
{
return array(
...
'apply_filter' => new \Twig_Function_Method($this, 'applyFilter'),
);
}
Then, you have to define this function
public function applyFilter($context, $filterName)
{
// handle parameters here, by calling the
// appropriate filter and pass $context there
}
After this manipulations you'll be able to call in Twig:
{{ apply_filter(object, 'filterName') }}
Cheers ;)