I created a custom twig function in AppExtension Class. I need to call form_label() from this new function. ¿Is it posible? I tried but does not work:
from template I call:
{{ myFunc(form.someField) }}
public function myFunc( $field )
{
$html = form_label($field);
}
The idea is to render each form field in a different order/way than the form_widget(form) twig function. The "form_label()" function it's not reconized.
Thx for any suggestion.
I feel like this is the wrong approach to handle this. Extensions are for transforming data not really to manipulate the form definition itself.
First of all the order is defined as in the form type, so you can swap those around. To render the fields differently you can use form themes, or even rendering a custom form type.
Alternatively if its a one time thing (you could also create a macro for this) you can also instead of form_widget(form) order them in the way you like.
{{ form_start(form) }}
{{ form_row(form.field3) }}
{{ form_row(form.field1, { attr: { class: 'im-different' } }) }}
{{ form_row(form.field2) }}
{{ form_end(form) }}
Or even go deeper.
{{ form_start(form) }}
{{ form_row(form.field3) }}
<div>
{{ form_label(form.field1) }}
{{ form_widget(form.field1) }}
{{ form_errors(form.field1) }}
</div>
{{ form_row(form.field2) }}
{{ form_end(form) }}
To see these functions and how they all rendered by default you can look at form_div_layout.html.twig.
I agree with Jenne van der Meer and Nico Haase that your approach isn't particularly optimal. If I had the choice, I would go a different route: Instead of rendering in your function, render in twig, then pass the result to the function (like {{ myFunc(form_label(form), form) }}). Since you omit what your function actually needs and/or does, it's hard to provide further advice. However, I'm absolutely sure, that rendering can be done in twig before or after entering your function, via a macro/block, maybe even a form theme).
However, if you really really require your function to render the form field ... the following will possibly help you. I strongly advise against doing this, there's probably a better suited solution.
The form_label function is slightly more complex than a simple function. Instead, it uses twig's compile mechanisms to generate specific php code. It will eventually call:
FormRenderer::searchAndRenderBlock(FormView $view, string $blockNameSuffix, array $variables = [])
Diving deep into the compiler, the template call form_label(form, options) would be turned into:
$this->env->getRuntime('Symfony\Component\Form\FormRenderer')->searchAndRenderBlock(
$form, 'label', $options
);
where the $this->env seems to be the twig environment. That means, to call this in your twig extension you need to have access to the proper Twig environment, and then it should already work with the recipe I just provided. Especially if you can omit the options argument, I didn't take a deeper look into how that one's assembled (but it's probably just straight forward).
So your twig function must be defined via:
public function getFunctions(): array
{
return [
new TwigFunction('myFunc', [&$this, 'myFunc'], [
'needs_environment' => true, // <--- this!
'is_safe' => ['html'],
]),
];
}
public function myFunc(\Twig\Environment $env, $field) {
// other stuff
$html = $env->getRuntime(\'Symfony\Component\Form\FormRenderer\')->searchAndRenderBlock(
$field, 'label', $options
);
return $html;
}
Related
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.
In messages.en.yml:
variable_name: Welcome to %site_name% - %other_info%
In Twig
{{ 'variable_name'|trans( -here- ) }}
It's the -here- part I'm struggling to know how to pass data in. I must do it this way (above is just an example).
Maybe I'm misunderstanding the question but if I understand correctly, you only need to give an array as the first parameter of the trans filter.
{{ 'variable_name'|trans({'%site_name%': 'My Website'}) }}
And of course, values can be variables if you don't put them between quotes :
{{ 'variable_name'|trans({'%site_name%': 'My Website', '%other_info%': page_name}) }}
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 ;)