0

what i need :

  • i need to implement session in twig.

  • i have implemented logic of code in php but d"nt have any idea how to implement in twig.

  • i have refer link Accessing session from TWIG template.

here is code

              <?php
               session_start();
               if(isset($_SESSION["count"]))
               {
                 $accesses = $_SESSION["count"] + 1;
               }
               else
               {
               $accesses = 1;
               }
               $_SESSION["count"] = $accesses;
      ?>
   <html>
  <head>
 <title>Access counter</title>
 <script>
function callback()
{
   var page = "<?php echo $accesses; ?>";
               if (page >4)
               {
               alert("limit exceeded");         
               }
               else
               {
               alert("ok");                
               }
}
callback();

<p>You have visited this  <?php echo $accesses; ?> times today.</p>

    </body>
    </html>
Community
  • 1
  • 1
user2818060
  • 835
  • 5
  • 19
  • 41

1 Answers1

3

You don't "implement sessions in Twig", period. You implement sessions in PHP code, and then pass any information that you may want to display in your HTML template to Twig to render. E.g.:

session_start();
$_SESSION['count'] ... // do whatever you want here to count

$twig = new Twig_Environment(...);
echo $twig->render('my_template.twig', ['count' => $_SESSION['count']]);

This handles your session code, and then passes the session's count value to Twig. Inside your template, you can then output it:

<p>{{ count }}</p>

You can pass the entire $_SESSION array to Twig, so you have access to everything in it.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • can you please guide how could i implement this in symphony custom functions – user2818060 Sep 17 '14 at 09:40
  • I have not used the entirety of Symfony yet, so no. If you need help specifically with that, ask a new question specifically for that. – deceze Sep 17 '14 at 09:47
  • can help var page = ""; when i want to call function count in javascript in twig . – user2818060 Sep 17 '14 at 10:39
  • 1
    `var page = {{ count }};` (Or `{{ accesses }}`, or whatever you name the value as when passing it to Twig.) – deceze Sep 17 '14 at 10:51
  • problem im facing is that there is no alert when web page is also reloded i have asked question in stackoveflow http://stackoverflow.com/questions/25887673/how-to-use-session-in-symphony-using-custom-twig-extension – user2818060 Sep 17 '14 at 11:01
  • please tell why my alert is not working inn twig file where i have done wrong . – user2818060 Sep 17 '14 at 11:05
  • i have also tried {% block myJavascript %} {% endblock %} but still not working – user2818060 Sep 17 '14 at 11:23