简体   繁体   English

如何在Twig中使用Sessions

[英]How to use Sessions in Twig

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. 我已经在php中实现了代码逻辑,但不知道如何在树枝上实现。

  • i have refer link Accessing session from TWIG template . 我已经从TWIG模板引用链接访问会话

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>

You don't "implement sessions in Twig", period. 期间,您不会“在Twig中实施会话”。 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. 您可以用PHP代码实现会话,然后将可能要显示在HTML模板中的所有信息传递给Twig进行渲染。 Eg: 例如:

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. 这将处理您的会话代码,然后将会话的计数值传递给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. 您可以将整个$_SESSION数组传递给Twig,因此您可以访问其中的所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM