Shopware6中在Twig模板获取Session变量的方法
在Shopware6 Twig模板中获取自定义Session变量的方法
方法一:直接通过Twig全局变量访问
Shopware6的Twig环境已内置app.session全局变量,可直接在模板中调用获取自定义Session值:
{# 假设你设置的Session键为'my_custom_session_key' #} {{ app.session.get('my_custom_session_key') }}
如需判断变量是否存在,可使用:
{% if app.session.has('my_custom_session_key') %} <p>自定义Session值:{{ app.session.get('my_custom_session_key') }}</p> {% endif %}
方法二:通过控制器传递到模板(适合需要预处理的场景)
如果需要对Session值做预处理,或希望模板逻辑更清晰,可通过控制器中转:
- 在控制器中读取Session值并传递给模板:
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Shopware\Core\Framework\Routing\Annotation\Route; use Shopware\Storefront\Controller\StorefrontController; /** * @Route(defaults={"_routeScope"={"storefront"}}) */ class CustomSessionController extends StorefrontController { public function showSessionValue(Request $request): Response { $sessionValue = $request->getSession()->get('my_custom_session_key'); return $this->render('@Storefront/page/custom-session.html.twig', [ 'customSessionValue' => $sessionValue ]); } }
- 在对应Twig模板中直接使用传递的变量:
<p>自定义Session值:{{ customSessionValue }}</p>
关键注意事项
- 确保你在PHP类中是通过Shopware6的Session服务设置变量,示例如下:
use Symfony\Component\HttpFoundation\Session\SessionInterface; class CustomSessionService { private $session; public function __construct(SessionInterface $session) { $this->session = $session; } public function setCustomValue() { $this->session->set('my_custom_session_key', '自定义内容'); } }
- 若需在前端Vue组件中使用Session值,需在Twig渲染时将值注入到Vue的props或全局
window对象,再通过前端逻辑调用。
内容的提问来源于stack exchange,提问作者Muhammad Zahoor
相关产品推荐
相关产品推荐

