douqin7086 2013-02-01 12:48
浏览 29
已采纳

树枝:如何围捕?

I have a division in twig. Sometimes, the result can be with decimals and i need to have always a rounded up result.

Ex.

7 / 2 = 3.5

I would like to have

7 / 2 = 4

I know how to use floor in twig:

7 / 2 | floor = 3

But this is rounding to the down digit, not to the upper one.

I know also that i can use number_format

7 / 2 | number_format(0, '.', ',') = 3

So this will also take the down digit.

Any idea on how to tell twig to take the upper digit ?

This can be done in a controller (Symfony), but I am looking for the twig version.

Thank you.

  • 写回答

8条回答 默认 最新

  • duankuiyu4618 2013-02-01 13:01
    关注

    Update

    On versions 1.15.0+, round filter is available.

    {{ (7 / 2)|round(1, 'ceil') }}
    

    http://twig.sensiolabs.org/doc/filters/round.html


    You can extend twig and write your custom functions as it is described here

    And it will be something like this:

    <?php
    // src/Acme/DemoBundle/Twig/AcmeExtension.php
    namespace Acme\DemoBundle\Twig;
    
    class AcmeExtension extends \Twig_Extension
    {
        public function getFilters()
        {
            return array(
                'ceil' => new \Twig_Filter_Method($this, 'ceil'),
            );
        }
    
        public function ceil($number)
        {
            return ceil($number);
        }
    
        public function getName()
        {
            return 'acme_extension';
        }
    }
    

    So you can you use it in twig:

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

报告相同问题?

悬赏问题

  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法