簡體   English   中英

無法訪問NULL變量(“”)上的屬性(“用戶名”)

[英]Impossible to access an attribute (“username”) on a NULL variable (“”)

嘗試通過put顯示登錄用戶的用戶名

{{ app.user.username }}

在base.html.twig給我一個錯誤

Impossible to access an attribute ("username") on a NULL variable ("") in ::base.html.twig at line 45

接受它就像

{{ app.security.getToken().getUser().getUsername() }}

導致以下錯誤。

Impossible to invoke a method ("getUser") on a NULL variable ("") 

如何在symfony中全局訪問登錄用戶的屬性? 如何修復錯誤?

嘗試首先檢查用戶是否存在,然后獲取其用戶名:

{% if app.user %}
    {{ app.user.username }} 
{% endif %}

或者使用三元運算符:

{{ app.user ? app.user.username }} 

如果username為空,您可以使用默認的 Twig過濾器來設置默認值:

 {{ app.user.username|default('undefined') }}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM