How to get params in twig file

11,428

Solution 1

hope it will help you

{% if app.request.get('comment') == "added" %}
    <script>alert("in TWIG file!");</script>
{% endif %}

Solution 2

Depending on what you're really trying to achieve, the "Symfony way" of showing confirmation messages would be to use "Flash Messages":

YourController.php:

public function updateAction()
{
    $form = $this->createForm(...);

    $form->handleRequest($this->getRequest());

    if ($form->isValid()) {
        // do some sort of processing

        $this->get('session')->getFlashBag()->add(
            'notice',
            'Your changes were saved!'
        );

        return $this->redirect($this->generateUrl(...));
    }

    return $this->render(...);
}

Your TwigTemplate.twig:

{% for flashMessage in app.session.flashbag.get('notice') %}
    <div class="flash-notice">
        {{ flashMessage }}
    </div>
{% endfor %}

This way you have multiple advantages:

  1. Redirecting after action prevents form reloading.
  2. Message cannot be triggered from outside.
  3. Flash messages are only fetched once.

See the official documentation on this topic.

Share:
11,428
Taner Deliloglu
Author by

Taner Deliloglu

www.animacoder.com

Updated on June 05, 2022

Comments

  • Taner Deliloglu
    Taner Deliloglu almost 2 years

    how can i use $_GET params in TWIG file like using PHP and alerting with JS.

    URI-> ?comment=added...

    in TWIG,

        if($_GET['comment'] == "added"){
         ...echo '<script>alert("in TWIG file!");</script>';
        }
    
    • Taner Deliloglu
      Taner Deliloglu almost 11 years
      i solved myself. {% if app.request.query.get('comment') == 'added' %} <script>alert('Added!');</script> {% endif %}