0

I have an issue with a cookie when in the controller in the same request I don't get it immediately available in the template.

However when I reload it appears.

Controller

        $response = $this->render(':frontend/homepage:homepage.html.twig');

        $now = new \DateTime();

        $response->headers->setCookie
        (
            new Cookie
            (
                'affiliateTracker',
                serialize
                (
                    array
                    (
                        'name' => 'John Doe'
                    )
                ),
                $now->modify('+24 hours'), '/'
            )
        );

        $response->sendHeaders();

        return $response;

Template

 {% if app.request.cookies.get('affiliateTracker') %}
                            <div class="alert text-center alert-success">
                                <i class="fa fa-user"></i> <strong>Your Name:</strong> {{ app.request.cookies.get('affiliateTracker').name }}
                            </div>
                        {% endif %}
Unsparing
  • 6,985
  • 2
  • 17
  • 33

1 Answers1

0

You can not get cookies immediately as it is written in this answer. One of the solutions is to get it on the client side using javascript:

<script>
  function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
if(getCookie('affiliateTracker') !== ""){
document.write( '<div class="alert text-center alert-success"><i class="fa fa-user"></i> <strong>Your Name:</strong>'+getCookie('affiliateTracker')+'</div>' );
}
</script>
Andrew Vakhniuk
  • 594
  • 4
  • 12