Reading list Switch to dark mode

    Symfony – How to get parameters value in Controller and Twig

    Updated 11 February 2016

    In Symfony, we defined various parameters in Parameters.yml so that our application can use these in various places. Example –

    parameters:
        database_host: 127.0.0.1
        database_port: null
        database_name: symfony
        database_user: root
        database_password: ''
        mailer_transport: smtp
        mailer_host: smtp.mydomain.com
        mailer_encryption: tls
        mailer_user: john
        mailer_password: ''
        secret: your-secret-key
    

    But how can we access these values in our Controller or Twig ? Simple 🙂 using getParameter function you can easily access these.

    $dataBaseName = $this->container->getParameter('database_name');
    

    To access these parameters you have to define these in Config.yml file, under twig key with globals keyword like database_name

    # Twig Configuration
    twig:
        globals:
            database_name: %database_name%
    

    using %% you can access defined values like we use $ in php for variables.

    Twig template code

    Searching for an experienced
    Symfony Company ?
    Find out More
    {{ database_name }}
    

    Symfony version used – 2.7

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    2 comments

  • Potworny
    • Webkul Support
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home