Cómo obtener parámetros de configuración en plantillas de ramitas Symfony2


Tengo una plantilla Symfony2 Twig. Quiero mostrar el valor de un parámetro de configuración en esta plantilla twig (un número de versión). Por lo tanto, definí el parámetro de configuración de esta manera:

parameters:
    app.version: 0.1.0

Puedo usar este parámetro de configuración en Controladores, pero no tengo ni idea de cómo obtenerlo en mi plantilla Twig.

Author: Habeeb Perwad, 2011-07-22

8 answers

Fácilmente, puede definir en su archivo de configuración:

twig:
    globals:
        version: "0.1.0"

Y acceder a ella en su plantilla con

{{ version }}

De lo contrario, debe ser una forma con una extensión Twig para exponer sus parámetros.

 178
Author: webda2l,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-22 20:33:02

Puede usar la sustitución de parámetros en la sección twig globals de la configuración:

Configuración del parámetro:

parameters:
    app.version: 0.1.0

Twig config:

twig:
    globals:
        version: '%app.version%'

Plantilla de ramita:

{{ version }}

Este método proporciona la ventaja de permitirle usar el parámetro en las clases ContainerAware también, usando:

$container->getParameter('app.version');
 375
Author: Ryall,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-16 17:58:41

También puede aprovechar el sistema integrado de Parámetros de servicio, que le permite aislar o reutilizar el valor:

# app/config/parameters.yml
parameters:
    ga_tracking: UA-xxxxx-x

# app/config/config.yml
twig:
    globals:
        ga_tracking: "%ga_tracking%"

Ahora, la variable ga_tracking está disponible en todas las plantillas de ramitas:

<p>The google tracking code is: {{ ga_tracking }}</p>

El parámetro también está disponible dentro de los controladores:

$this->container->getParameter('ga_tracking');

También puede definir un servicio como una variable ramita global (Symfony2.2+):

# app/config/config.yml
twig:
    # ...
    globals:
        user_management: "@acme_user.user_management"

Http://symfony.com/doc/current/templating/global_variables.html

Si el global variable que desea establecer es más complicado-digamos un objeto-entonces usted no será capaz de utilizar el método anterior. En su lugar, necesitará crear una extensión Twig y devolver la variable global como una de las entradas en el método getGlobals.

 82
Author: Francesco Casula,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-01 14:22:39

En las versiones más recientes de Symfony2 (usando un parameters.yml en lugar de parameters.ini), puede almacenar objetos o matrices en lugar de pares clave-valor, por lo que puede administrar sus globales de esta manera:

Config.yml (editado solo una vez):

# app/config/config.yml
twig:
  globals:
    project: %project%

Parámetros.yml:

# app/config/parameters.yml
project:
  name:       myproject.com
  version:    1.1.42

Y luego en un archivo twig, puede usar {{ project.version }} o {{ project.name }}.

Nota: Personalmente no me gusta agregar cosas a app, solo porque esa es la variable de Symfony y no se qué se almacenará allí en el futuro.

 20
Author: Alain Tiemblo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-05 15:32:51

Los an dados arriba son correctos y funcionan bien. Usé de una manera diferente.

Config.yml

imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: app.yml }
    - { resource: app_twig.yml }

App.yml

parameters:
  app.version:           1.0.1

App_twig.yml

twig:
  globals:
    version: %app.version%

Controlador interno:

$application_version = $this->container->getParameter('app.version');
// Here using app.yml

Dentro del archivo de plantilla / ramita:

Project version {{ version }}!
{#  Here using app_twig.yml content.  #}
{#  Because in controller we used $application_version  #}

Para usar la salida del controlador:

Controlador:

public function indexAction() {
        $application_version = $this->container->getParameter('app.version');
        return array('app_version' => $application_version);
    }

Archivo de plantilla / ramita:

Project version {{ app_version }}

Mencioné lo diferente para mejor entender.

 16
Author: Sudhakar Krishnan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-14 16:59:10

Con una extensión Twig, puede crear una función Twig parameter:

{{ parameter('jira_host') }}

Extensión de ramita.php:

class TwigExtension extends \Twig_Extension
{
    public $container;

    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('parameter', function($name)
            {
                return $this->container->getParameter($name);
            })
        ];
    }


    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'iz';
    }
}

Servicio.yml:

  iz.twig.extension:
    class: IzBundle\Services\TwigExtension
    properties:
      container: "@service_container"
    tags:
      - { name: twig.extension }
 11
Author: Thomas Decaux,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-04 17:00:25

Simplemente puedes enlazar $this->getParameter('app.version') en el controlador a twig param y luego renderizarlo.

 1
Author: Jean-Luc Barat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-07 11:29:54

En confing.yml

# app/config/config.yml
twig:
  globals:
    version: '%app.version%'

En la vista Ramita

# twig view
{{ version }}
 -3
Author: Le Petit Monde de Purexo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-03 14:48:23