You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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值做预处理,或希望模板逻辑更清晰,可通过控制器中转:

  1. 在控制器中读取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
        ]);
    }
}
  1. 在对应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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 12:00:59