Symfony 3 Translations Custom Domain - symfony

I'm trying to add custom domain into the project.
I have regions.locale.yaml file.
I'm trying load it in twig:
{{'united.kingdom'|trans|raw}}
But this doesn't work.
I think it has to be somehow declared that this file exists.
I found this in documentation:
// ...
$translator->addLoader('xlf', new XliffFileLoader());
$translator->addResource('xlf', 'messages.fr.xlf', 'fr_FR');
$translator->addResource('xlf', 'admin.fr.xlf', 'fr_FR', 'admin');
$translator->addResource(
'xlf',
'navigation.fr.xlf',
'fr_FR',
'navigation'
);
But where should I put this to declare my regions.locale.yaml files globally?
Thanks

If you are using Symfony Standard, you don't have to declare your translation files, you just put them in app/Resources/translations.
The key is that when you want to translate using your custom domain, you just specify your domain, like this :
{{'united.kingdom'|trans({}, 'regions')|raw }}
or somewhere else in your code :
$translator->trans('united.kingdom', [], 'regions');

Related

How to use anchors in Symfony routing?

I have defined a route as followed in my routing.yml file :
route_name:
path: "/dashboard#messages/{id}"
However when I ask Symfony to generate that route, I get :
/dashboard%23messages/12345
How can I skip the encoding part of the route generation? Or how can I escape the # char in the path definition?
PS : Working with a (big) legacy system, I cannot change the urls.
Available from Symfony 3.2.
Support for anchors has been announced for the routing component using the fragment variable :
$this->get('router')->generate('user_settings', ['_fragment' => 'password']);
Will generate an url : /user/settings#password
For more information view the announcement.
You cannot easily - route parts are encoded unconditionally:
$url = strtr(rawurlencode($url), $this->decodedChars);
see at https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Routing/Generator/UrlGenerator.php#L192
Technically you might have extended the class UrlGenerator class and swap them using router.options.generator_class parameter. Then you could override the doGenerate method and replace %23 -> #.
In twig
<a href="{{ path('user_settings', { '_fragment': 'password' }) }}">

Twig Loader prependPath not working

I'm trying to use theme in symfony 2.5.6 following this tutorial : http://www.ahmed-samy.com/symofny2-twig-multiple-domains-templating/
So I tried this in the TemplateListener (declared as service)
$path = dirname(__DIR__) . '/Resources/themes/' . $theme . '/views';
$this->twig->getLoader()->prependPath($path, 'MyWebsiteFront');
But this does not work, the template "MyWebsiteFront:Index:index.html.twig" is not found (but it exists at C:\www\MyWebsiteFront\src\MyWebsiteFront\Resources\themes\mytheme\views\Index\index.html.twig, the path generated by $path)
Any ideas ?
According to the docs, When you render the template you need to reference it with the namespace you aliased to that path e.g.
#MyWebsiteFront/Index/index.html.twig
When using the setPaths(), addPath(), and prependPath() methods,
specify the namespace as the second argument (when not specified,
these methods act on the "main" namespace):
$loader->addPath($templateDir, 'admin'); Namespaced templates can be
accessed via the special #namespace_name/template_path notation:
$twig->render('#admin/index.html', array());
NOTE: The namespace is not required.

How to use symfony2 twig extension without symfony2

I want to use some of the builtin symfony2 extensions(e.g:humanize,yaml_dump) for twig for a website not developed in symfony but using a twig engine.how can I do that?
The symfony/twig-bridge package provides the symfony-specific twig extensions.
These include i.e. the YamlExtension that provides the yaml_dump filter and the FormExtension that provides the humanize filter.
The extensions can be found in the Extension folder.
I strongly advise you to install the package via composer to get the package's dependencies automatically.
composer require symfony/twig-bridge:~2.3
Further composer will automatically register the classes in the autoloader (vendor/autoload.php) for you.
Now you just need to add the extensions to twig as described in the documentation.
$twig->addExtension(new \Symfony\Bridge\Twig\Extension\YamlExtension());
// ...
A complete example, with an extension class and a quick extension (a new filter) :
<?php
require_once("vendor/autoload.php");
$loader = new Twig_Loader_String();
$twig = new Twig_Environment($loader);
// here we add the extension class (taken from #nifr answer)
$twig->addExtension(new \Symfony\Bridge\Twig\Extension\YamlExtension());
// here we add a new filter quickly
$filter = new Twig_SimpleFilter('paragraph', function ($argument) {
return "<p>{$argument}</p>";
}, array('pre_escape' => 'html', 'is_safe' => array('html')));
$twig->addFilter($filter);
// demo
echo $twig->render('{{ "hello" | paragraph }}');

Limit languages in cms

I use silverstripe 3.1
I would like to limit the languages (To only German and English) which are available in the drop down in the CMS. Therefore I put
the following code in my mysite/_config.php
i18n::set_locale('de_DE');
$allowed_locales = array(
'de_DE' => array('Deutsch', 'Deutsch'),
'en_EN' => array('English', 'English')
);
i18n::$common_locales = $allowed_locales;
Afer a flush=1 i get the following error:
Fatal error: Cannot access private property i18n::$common_locales in ... _config.php
Any ideas what goes wrong?
Thank you
as of 3.1 most of the static php variables are private. this means you can no longer access those.
the reason for this api change is that they are now cached by the config layer (this is also why you have to ?flush=1 now after changing private statics in classes like for example with private static $db)
if you want to update something in the config layer, you can do this with:
Config::inst()->update('CLASS', 'FIELD', $value);
you could use use the config update to overwrite the common locales (class would be 'i18n', and field would be 'common_locales'):
Config::inst()->update('i18n', 'common_locales', $array);
Note: if you want to completely overwrite an existing configuration, you have to do a remove() first.
Config::inst()->remove('i18n', 'common_locales');
Config::inst()->update('i18n', 'common_locales', $array);
however, if you are using the translatable module and you want to limit the number of translatable languages, there is a much better way already built in:
// in your _config.php
i18n::set_locale('en_US');
Translatable::set_allowed_locales(array(
'de_DE',
'en_US',
));
Config it through YAML:
i18n:
common_locales:
nl_BE:
name: Dutch (Belgium)
native: Nederlands
fr_BE:
name: French (Belgium)
native: Francais

Custom route configuration with Silex

I know that the basis of Silex approach in which all the application logic in a single file. But my application will be possible to have more than twenty controllers. So I want to have a handy map to manage the router.
My question is to search for solutions in which I would be able to make a router to a separate file. In the best case, the file must be of YAML type:
# config/routing.yml
_home:
pattern: /
defaults: { _controller: MyProject\Controller\MyController::index }
But the native is also a good case (for me):
$routes = new RouteCollection();
$routes->add(
'home',
new Route('/', array('controller' => 'MyProject\Controller\MyController::index')
));
return $routes;
Problem of the second case is that I have to use the match() function for each rule of routing. It is not at all clear.
What are the ways to solve this issue? The condition is that I want to use the existing API Silex or components of Symfony2.
Small note:
I don't use a ControllerProviderInterface for my Controller classes. This is an independent classes.
First of all, the basis of Silex is not that you put everything in one file. The basis of Silex is that you create your own 'framework', your own way of organizing applications.
"Use silex if you are comfortable with making all of your own architecture decisions and full stack Symfony2 if not."
-- Dustin Whittle
Read more about this in this blogpost, created by the creator of Silex.
How to solve your problem
What you basically want is to parse a Yaml file and get the pattern and defaults._controller settings from each route that is parsed.
To parse a Yaml file, you can use the Yaml Component of Symfony2. You get an array back which you can use to add the route to Silex:
// parse the yaml file
$routes = ...;
$app = new Silex\Application();
foreach ($routes as $route) {
$app->match($route['pattern'], $route['defaults']['_controller']);
}
// ...
$app->run();
I thought I'd add my method here as, although others may work, there isn't really a simple solution. Adding FileLocator / YamlFileLoader adds a load of bulk that I don't want in my application just to read / parse a yaml file.
Composer
First, you're going to need to include the relevant files. The symfony YAML component, and a really simple and useful config service provider by someone who actively works on Silex.
"require": {
"symfony/yaml": "~2.3",
"igorw/config-service-provider": "1.2.*"
}
File
Let's say that your routes file looks like this (routes.yml):
config.routes:
dashboard:
pattern: /
defaults: { _controller: 'IndexController::indexAction' }
method: GET
Registration
Individually register each yaml file. The first key in the file is the name it will be available under your $app variable (handled by the pimple service locator).
$this->register(new ConfigServiceProvider(__DIR__."/../config/services.yml"));
$this->register(new ConfigServiceProvider(__DIR__."/../config/routes.yml"));
// any more yaml files you like
Routes
You can get these routes using the following:
$routes = $app['config.routes']; // See the first key in the yaml file for this name
foreach ($routes as $name => $route)
{
$app->match($route['pattern'], $route['defaults']['_controller'])->bind($name)->method(isset($route['method'])?$route['method']:'GET');
}
->bind() allows you to 'name' your urls to be used within twig, for example.
->method() allows you to specify POST | GET. You'll note that I defaulted it to 'GET' with a ternary there if the route doesn't specify a method.
Ok, that's how I solved it.
This method is part of my application and called before run():
# /src/Application.php
...
protected function _initRoutes()
{
$locator = new FileLocator(__DIR__.'/config');
$loader = new YamlFileLoader($locator);
$this['routes'] = $loader->load('routes.yml');
}
Application class is my own and it extends Silex\Application.
Configuration file:
# /src/config/routes.yml
home:
pattern: /
defaults: { _controller: '\MyDemoSite\Controllers\DefaultController::indexAction' }
It works fine for me!
UPD:
I think this is the right option to add collections:
$this['routes']->addCollection($loader->load('routes.yml'));
More flexible.
You could extend the routes service (which is a RouteCollection), and load a YAML file with FileLocator and YamlFileLoader:
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Routing\Loader\YamlFileLoader;
$app->extend('routes', function($routeCollection) {
$locator = new FileLocator([__DIR__ . '/../config']);
$loader = new YamlFileLoader($locator);
$collection = $loader->load('routes.yml');
$routeCollection->addCollection($collection);
return $routeCollection;
});
You will need symfony/config and symfony/yaml dependencies though.

Resources