Twig: Set default translation language - symfony

there is situation like this:
example.twig.html
<P>{%trans%}Example Message 1{%endtrans%}</P>
<P>{%trans%}Example Message 2{%endtrans%}</P>
<P>{%trans%}Example Message 3{%endtrans%}</P>
This is not template to show by visitor via web browser, but to send on mail
randomTroll#randomDomain.randomCountry
by Swift_Message.
I want to force change default laguage to Trollish, but I do not want to use this:
{%trans into 'trollish' %}...{% endtrans %}
every time. It works perfectly, but it is ugly like a troll after washing in swamp.
In controller i tried something like this before render('example.twig.html'):
$request->setLocale('trollish');
$this->get('session')->set('_locale', 'trollish');
then
{{ app.request.locale }}
returns "trollish"
but used language in {% trans %}...{ %trans% } still is not trollish :(
How i can fix that?

In your controller, add:
$this->get('translator')->setLocale('trollish');

Related

Get the domain name in Twig/Timber to output in WordPress?

When I have an error in my custom WordPress theme I would like to output the webmaster email address which would be webmaster#mydomainname.com but I am a bit baffled on how to do this in Twig/Timber in the most straightforward way: <p class="text-danger fw-bold">PAGE ERROR - Please contact Webmaster at webmaster#{{ #notsure# }}</p>
webmaster#{{ site.url }} just outputs: webmaster#https://mywordpress.local which obviously won't work.
UPDATED: To get by I am using webmaster#{{ site.url[8 :] }} as that strips away the https:// and outputs webmaster#mywordpress.local but seems there should be a cleaner way somehow?
There are two ways to do this:
You can use Advanced custom field. Make a email field and then print that value inside the twig file. Inside advanced custom field, you can add any email you have no need to extract a domain name. For more information follow this reference: https://timber.github.io/docs/guides/acf-cookbook/
Second method is the way you doing is correct but you need to split domain name from site.url using slice method:
{% set website = "https://mywordpress.local" %} //
//calcualting length of string
{% set lengthOfWebsite = website|length %}
//using length here to split the string accordingly. 8is for split "https://" from actual domain name.
{% set domainName = website|slice(8,lengthOfWebsite) %}
webmaster#{{domainName}}
For the first line of code in your case will be:
{% set website = site.url %}
For the last line
webmaster#{{domainName}}
can also be replaced by:
{% set actualDomainName = 'webmaster#' ~ domainName %}
{{actualDomainName}}

Display dynamically informations in a Symfony layout

I have a layout included in another one that display my menu. The labels of my menu items need to be dynamic (like the unread messages number of a mailbox). Then I did this :
My orders
(
{{ render(controller('MyController', {'etat':2})) }}
<span style="color:red">with {{ render(controller('MyController', {'etat':2})) }} in late</span>
)
I would like to display labels according to the number that return my controller. I don't know how to get it in a variable.
When rendering your template in your controller
return $this->render('twig_template_name.html.twig', array('variable_name' => $variable);
you pass a variable to the twig template in the array of options as I showed. Your code
{{ path('mypath',{'etat': '2' }) }}
prints a path defined in the routing.yml under the 'mypath' section and ends up adding a GET request variable to the link ('?etat=2'), if 'mypath' showed an absolute route 'www.website.com/yourpath',
{{ path('mypath',{'etat': '2' }) }} would produce 'www.website.com/yourpath?etat=2', which would send your controller for a route /yourpath/{etat} a variable etat with a value of 2 so all you need to do now is change 2 with an actual dynamic value which you receive from another controller.
I am not sure what etat is but lets say it's an article and it has it's id, you have a blog page with lots of articles and the controller that prints them all out sends an array of articles to the twig template, on your twig template you do something like:
{% foreach article in articles %}
{{ article.title }}
{{ article.story }}
read more
{% endforeach %}
And you end up something like:
Catchy Title
Awesome story about code without bugs and where deadlines depend on how creative and well designed and implemented the solutions are
[read more]
and you ofcourse click on "read more" and end up on the url ~/article/2 because the article had an id of 2, your controller for that url receives a variable id in the request, you do a $id = $_GET['id']; and grab the article from the repository and send it to the template.
Hopefully this answered your question, I am very tiered so forgive me if i was confusing which I surely was.

Cannot render text filtered with trans in twig template using Sandbox Security Policy

I am a little bit confused. First of all, look at my code, I guess.
public function renderTemplate($templateType, $data)
{
$layoutName = "$templateType.layout.html.twig";
$policy = new \Twig_Sandbox_SecurityPolicy(
['if', 'for', 'block', 'set', 'extends'],
['escape', 'format', 'dateformat', 'trans', 'raw', 'striptags'],
self::$allowedMethods,
self::$allowedProperties,
['gettext']
);
$sandboxExt = new \Twig_Extension_Sandbox($policy);
$intlExt = new \Twig_Extensions_Extension_Intl();
$i18nExt = new \Twig_Extensions_Extension_I18n();
$twig = new \Twig_Environment(new \Twig_Loader_Filesystem(__DIR__ . "/../Resources/views/Something/", "__main__"));
$sandboxExt->enableSandbox();
$twig->addExtension($sandboxExt);
$twig->addExtension($intlExt);
$twig->addExtension($i18nExt);
try {
$result = $twig->render($layoutName, $data);
} catch (\Exception $e) {
\Doctrine\Common\Util\Debug::dump($e);die();
}
return $result;
}
Here it is the template I want to render
{% extends 'layout.html.twig' %}
{% block title %}{{ entity.id }}{% endblock %}
{% block bodyTitle %}
{{ entity.id }} {{ 'translation_key.created_at'|trans({}, 'entities', locale) }} {{ entity.createdAt|dateformat(null, locale) }}
{% endblock %}
Here, as you can see, I want to render a template according to its type. The problem is: half of the template renders just fine, and then, when it tries to render the translated string, it throws an error.
Fatal error: Call to undefined function gettext() in /home/dev/vhosts/my-project/vendor/twig/twig/lib/Twig/Environment.php(403) : eval()'d code on line 69
I checked if this function existed right before trying to call render method, and it was really undefined. Basically, I have 2 questions here:
Question 1
How does it work in other parts of my project, but not in this specific handler? See "Important update" below.
Question 2
Can I solve my problem in another way? For example, without using Sandbox or using Sandbox with some kind of a flag "everythingAllowed=true"?
ATTENTION! IMPORTANT UPDATE
Previously, I misunderstood my own question. I thought the error was thrown while rendering the variable, but I re-checked the situation (When Alain Tiemblo asked me for twig template code here in comments) and now 100% sure it's thrown while trying to translate smth. Also, I have translations all over my project, and it works just fine, but in this specific situation it's not. I think it worth to mention, that I also tried to render the template without using Sandbox. I tried to render it directly from Twig Engine like this
return $this->templating->render($layoutName, $data);
//$this->templating is injected in the constructor via services.yml like this
//arguments:
// - "#templating"
The result - not properly translated text. When I dumped "locale" - I got one specific language, but the text was translated in another. But at least using this method - I didn't get any errors.. Can anybody clarify this for me? Because I really don't understand how the Intl/i18n extension works and why it doesn't want to work in Sandbox or not in Sanbox?
P.S. My guess, why it doesn't work directly from Twig Engine - probably I should inject not like "#templating" or it injects just right, but the Intl or I18n extensions are not enabled? How to enable. And I have no clues why it doesn't work with Sandbox

Translate the value of twig variable

Is it possible to translate the value of twig variables in a template with the 'trans' tag?
Say for instance I am passing a product to my template. This product has a definition with a trans tag e.g {{ product.definition|trans }}. This definition could either be in EN or DE or some other language. How could I translate the definition.
What are you trying to do is not a good way, It would look like this:
messages.en.yml
product:
definition:
some_value1: Some value 1
some_value2: Some value 2
and in template, you would do something like this:
{% set definition_value = product.definition %}
{% set trans_definition = 'product.definition.' ~ definition_value %}
{{ trans_definition|trans }}
it'll work, if it finds the key. What if it cant find it?
That's why you should use DoctrineBehaviors from KnpLabs, which handles all the dynamic translations for you..
If {{ product.definition }} equals 'cellphone' the following should work.
message.language.yml:
'cellphone': This will work!
However if you want to map it with the 'product' key in your message file like this:
product:
'cellphone': This also works
add the key to the twig template like so:
{{('product.'~product.definition)|trans }}

How to get the current page name in Silex

I'm wondering how to get the current page name, basically 'just' the last parameter in the route (i.e. /news or /about). I'm doing this because I want to be able to have the current page in the navigation highlighted.
Ideally, I'd like to store the current page name in a global variable so that in Twig I can just compare the current page name against the link and add a class accordingly.
I can't figure out how to add the current page name to a global variable though. I've tried using something like this:
$app['twig']->addGlobal('current_page_name', $app['request']->getRequestUri());
at the top of my app.php file, but an 'outside of request scope' error. But I wouldn't like to have to include this in every route.
What's the best way to do this?
If you put it into an app-level before middleware like this, that'll work:
$app->before(function (Request $request) use ($app) {
$app['twig']->addGlobal('current_page_name', $request->getRequestUri());
});
The "page name" part of your question is unclear, are you looking for the current route's name? You can access that via $request->get("_route") even in the before middleware, as it gets called when routing is already done.
You could also generate navigation list directly in stand alone nav twig template. And then import it in to the main template. Then you would only have to get silex to pass to the view the current page identifier. Simplest way... for example from Silex you would have to pass in the "path" variable to your view. Probably it would more convenient to to fetch nav_list from database and pass it in to twig template as global array variable instead. However this example is the simplest you could get to do what you intend.
nav.twig
{% set nav_list = [
["./", "home"],
["./contact", "contact"],
["./about", "about us"]
{# ... #}
] %}
{% set link_active = path|default("") %}
{% for link in nav_list %}
<li><a href="{{ link[0] }}" class="{% if link[0] == link_active %} activeClass {% endif %}" >{{ link[1] }}</a></li>
{% endfor %}
app.php
//...
$app->match('/about', function (Request $request) use ($app) {
return $app['twig']->render('about.twig', array(
'path' => './'.end(explode('/', $request->getRequestUri()))
));
});
//...

Resources