Obsługa wartości null w Freemarkerze

Jak obsĹ 'ugiwaÄ ‡ null wartoĹ" ci w Freemarkerze? Dostaję wyjątki w szablonie, gdy null wartości są obecne w danych.

 57
Author: Nathan, 2012-12-19

4 answers

Możesz użyć ?? operatora testowego:

Sprawdza, czy atrybut obiektu nie jest null:

<#if object.attribute??></#if>

Sprawdza, czy obiekt lub atrybut nie jest null:

<#if (object.attribute)??></#if>

Source: FreeMarker Manual

 73
Author: Tom Verelst,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-12 16:19:24

Począwszy od freemarkera 2.3.7, możesz użyć tej składni :

${(object.attribute)!}

Lub, jeśli chcesz wyświetlić domyślny tekst, gdy atrybutem jest null:

${(object.attribute)!"default text"}
 62
Author: Super Chafouin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-23 04:46:46

Myślę, że to działa w drugą stronę

<#if object.attribute??>
   Do whatever you want....
</#if>

Jeśli object.attribute nie jest równe NULL, wtedy zawartość zostanie wydrukowana.

 2
Author: Senthil Kumar Sekar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-25 20:24:56

Użycie ?? operator na końcu twojego <#if> Oświadczenia.

Ten przykład pokazuje, jak obsługiwać wartości null dla dwóch list w szablonie Freemaker.

List of cars:
<#if cars??>
    <#list cars as car>${car.owner};</#list>
</#if>
List of motocycles:
<#if motocycles??>
    <#list motocycles as motocycle>${motocycle.owner};</#list>
</#if>
 0
Author: Daniel Perník,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-25 20:26:00