How to Use Session in Symfony using Custom Twig Extension(如何使用自定义 Twig 扩展在 Symfony 中使用 Session)
问题描述
我需要什么
- 我只想在 symfony 中实现会话.
这是我尝试过的
/src/Acme/bundlename/Twig
/src/Acme/bundlename/Twig
Acmeextension.php
Acmeextension.php
public function getFunctions()
{
return array(
'count' => new Twig_Function_Method($this, 'count'),
);
}
public function count()
{
session_start();
if(isset($_SESSION["count"]))
{
$accesses = $_SESSION["count"] + 1;
}
else
{
$accesses = 1;
}
$_SESSION["count"] = $accesses;
return $accesses;
}
这里是twig的代码:
here is the code of twig:
function callback()
{
var page = {{ count}};
if (page >4)
{
alert("limit exceeded");
}
else
{
alert("ok");
}
}
callback();
calling in twig
{{ count }}
- 我只想计算浏览量.
- 我在 twig 中使用了脚本,因此如果页面浏览量超过 4 次,则显示警报消息.
- 我使用了 symfony 自定义函数,以便在 symfony 中使用 $SESSION.
- 我已经在核心 PHP 中实现了这段代码,它工作正常.
我参考了链接 将会话传递给 TWIG 模板.
自定义 Twig 扩展 http://symfony.com/doc/current/cookbook/template/twig_extension.html
custom Twig Extension http://symfony.com/doc/current/cookbook/templating/twig_extension.html
问题
- 当我重新加载页面时,我不会收到任何警报.
- 请告诉我我哪里错了,欢迎提出任何建议.
推荐答案
如果您希望将超出范围含义的会话注入自定义扩展.
If you are looking to inject sessions outside of the scope meaning into your custom extension.
我会这样做.
//AppKernel +add protected function initializeContainer() { parent::initializeContainer(); if (PHP_SAPI == 'cli') { $this->getContainer()->enterScope('request'); $this->getContainer()->set('request', new SymfonyComponentHttpFoundationRequest(), 'request'); } }
然后在你的服务容器中
<!-- Custom Twig Extensions --> <service id="yourid" class="yourclasspath"> <argument type="service" id="service_container" /> <tag name="twig.extension" /> </service>
然后在你的 twig.php 中
Then in your twig.php
class Twig extends Twig_extension { private $request; public function __construct(Container $container) { $this->request = $container->get('request'); } public function getFunctions() { return array( 'count' => new Twig_Function_Method($this, 'count'), ); } public function count() { $session = $this->request->getSession(); if(session->has('count')) { $session->set('count') += 1; } else { $session->set('count') = 1; } return $session->get('count'); } }
然后在你的树枝上也一样
Then the same in your twig
这篇关于如何使用自定义 Twig 扩展在 Symfony 中使用 Session的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用自定义 Twig 扩展在 Symfony 中使用 Session


基础教程推荐
- 如何替换eregi() 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01