Reputation: 43
We have a Symfony 3.4 project with twig templates and authentication system by FOSUserBundle.
It is multi-domain and manages customer and supplier data mainly works well but now I have a problem that I do not know how to solve at the time of user registration.
I need that depending on the domain, it can show one or another twig template at the time of registration.
Search documentation and find how to write custom twig extension https://symfony.com/doc/3.4/templating/twig_extension.html
This is my function and almost like the one in the example
<?php
// src/AppBundle/Twig/AppExtension.php
namespace AppBundle\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class AppExtension extends AbstractExtension
{
public function getFunctions()
{
return [
new TwigFunction('server', [$this, 'serverName']),
];
}
public function calculateArea(int $width, int $length)
{
return $width * $length;
}
public function serverName()
{
$serverName = "$_SERVER[SERVER_NAME]";
return $serverName;
}
}
The question is, how can I use my function in Twig? I need that based on the domain in which it connects, it showed us a registration form or something like this:
{% extends "@FOSUser/layout.html.twig" %}
{% block fos_user_content %}
{% if serverName == "xxxxx"%}
{% include "@FOSUser/Registration/register_content_cliente.html.twig" %}
{% else %}
{% include "@FOSUser/Registration/register_content_proveedor.html.twig" %}
{% endif %}
{% endblock fos_user_content %}
It does not work like that:
{{ serverName }}
{{ server }}
{% serverName %}
{% server %}
Upvotes: 4
Views: 1936
Reputation: 17166
Just as with php you have to call a function using ()
, so serverName()
server()
, as this is what you call the function in AppExtension::getFunctions()
(first argument).
You might want to replace that function with a so called test. Then you can do something like:
{% if 'example.com' is serverName %}
{% endif %}
The code could look something like:
class AppExtension extends AbstractExtension
{
public function getTests()
{
return [
new TwigTest('serverName', [$this, 'isServerName']),
];
}
public function isServerName(string $serverName)
{
return $serverName === $_SERVER[SERVER_NAME];
}
}
Alternatively in your templates you always have access to the request with the variable app.request
which you can ask for the current server name using one of the methods on Symfony's Request object. For example you can use Request::getHost()
for the comparison:
{% if app.request.host == 'example.com' %}
{% endif %}
No function or test or other twig extension necessary.
Upvotes: 3