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 基于作物生长模型下,有限水资源的最大化粮食产量的资源优化模型建立
  • ¥20 关于变压器的具体案例分析
  • ¥15 生成的QRCode圖片加上下載按鈕
  • ¥15 板材切割优化算法,数学建模,python,lingo
  • ¥15 科来模拟ARP欺骗困惑求解
  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式