doumu6997 2015-09-23 12:17
浏览 27
已采纳

Twig过滤器链接和优先级

I'm having diffculties trying to find the right syntax for a multiple Twig filter expression.

I have a var called floatVar which is not always defined.

If it is defined, I would like to truncate this float to the third digit. If it is not defined, I would like to set an empty string.

I'm having trouble finding the proper syntax:

floatVar|number_format(3, '.','')|default('') // generates a Twig_Error_Runtime exception

floatVar|default('')|number_format(3, '.','') // output "0" in every case

(floatVar|number_format(3, '.',''))|default('') // generates a Twig_Error_Runtime exception

Could somebody point me in the right direction ? Is there a way to put paranthesis to explictly express the priority ? Any help or link to a related topic would be much appreciated.

Have a good day.

  • 写回答

2条回答 默认 最新

  • douwu0882 2015-09-23 13:06
    关注

    The correct order would be :

    {{ floatVar|default(0)|number_format(3, '.','') }}
    
    • default(0) : first you ensure that floatVar has a default value (even if it's not defined)
    • number_format(3, '.','') : then you format it

    however, this would print 0.000 if floatvar isn't defined.

    if you want to do this in 1 line, you should consider creating a custom twig extension : http://symfony.com/doc/current/cookbook/templating/twig_extension.html

    EDIT : Following @Pierre Olivier's answer, you should try :

    {{ floatVar is defined ? floatVar|number_format(3, '.','') : '' }}
    

    (yourelement != null will raise an error if yourelement isn't defined)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 从Freecad中宏下载的DesignSPHysics,出现如下问题是什么原因导致的(语言-python)
  • ¥30 notepad++ 自定义代码补全提示
  • ¥15 MATLAB有限差分法解一维边值问题
  • ¥200 内网渗透测试 横向渗透 Windows漏洞 Windows权限维持
  • ¥15 数据结构图的相关代码实现
  • ¥15 python中aiohttp.client_exceptions.ContentTypeError
  • ¥30 DeepLung肺结节检测生成最大froc值对应的epoch报错
  • ¥15 信号发生器如何将频率调大,步尽值改成10
  • ¥15 keil 5 编程智能家具,风扇台灯开关,人体感应等
  • ¥100 找一名渗透方面的专家