【问题标题】:Generate random hexadecimal colour in Twig在 Twig 中生成随机的十六进制颜色
【发布时间】:2017-06-15 09:19:43
【问题描述】:

我想在 Twig 中生成随机的十六进制颜色,例如将其用作这样的背景:

{% for organization in organizations %}
    {
        value: {{ organization.value }},
        color: "#F56954",
        label: "{{ organization.name }}"
    },
{% endfor %}

有什么办法吗?

【问题讨论】:

    标签: symfony colors twig hex


    【解决方案1】:
    class SomeUtil
    {
        /**
         * @return string hex color string (RGB): #XXXXXX
         */
        public static function randHexColor()
        {
            return sprintf("#%06s", dechex(rand(0, 256**3-1)));
        }
    
        /**
         * @param int $rangeFrom [0..255]
         * @param int $rangeTo [0..255]
         * @return string hex color string (RGB): #XXXXXX
         */
        public static function rangedRandHexColor($rangeFrom = null, $rangeTo = null)
        {
            $min = 0;
            $max = 255;
            if ($rangeFrom === null || !NumberUtil::inRange($rangeFrom, $min, $max)) {
                $rangeFrom = $min;
            }
            if ($rangeTo === null || !NumberUtil::inRange($rangeTo, $min, $max)) {
                $rangeTo = $max;
            }
            if ($rangeFrom === $min && $rangeTo === $max) {
                return self::randHexColor();
            } else {
                return sprintf("#%02s", dechex(rand($rangeFrom, $rangeTo)))
                    .sprintf("%02s", dechex(rand($rangeFrom, $rangeTo)))
                    .sprintf("%02s", dechex(rand($rangeFrom, $rangeTo)));
            }
        }
    
    }
    

    在控制器中

    $data['util'] = new SomeUtil();
    
    return $this->renderView('AppBundle:Foo:bar.html.twig', $data);
    

    在树枝上

    {{ util.randHexColor() }}
    

    {{ util.rangedRandHexColor(180, 220) }}
    

    排除深色和 LSD 颜色

    【讨论】:

      【解决方案2】:

      我建议您将一组已知数据随机化(以排除无意义值),如下所示:

      {% for organization in organizations %}
          {
              value: {{ organization.value }},
              color: "{{ random(['#H54924', '#F36252', '#F56954']) }}"
              label: "{{ organization.name }}"
          },
      {% endfor %}
      

      编辑:

      对于纯随机值,可以尝试以下方法:

      {% set values = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']%}
      {% for organization in organizations %}
          {
              value: {{ organization.value }},
              color: "#{{random(values)~ random(values)~ random(values)~ random(values)~ random(values)~ random(values)  }}",
              label: "{{ organization.name }}"
          },
      {% endfor %}
      {{ '#' ~ random(values) ~ random(values) ~ random(values) ~ random(values) ~ random(values) ~ random(values)  }}
      

      Here 一个工作示例

      希望有帮助

      【讨论】:

        猜你喜欢
        • 2016-02-04
        • 2015-10-07
        • 2012-12-09
        • 2011-12-29
        • 1970-01-01
        • 2014-07-03
        • 2018-08-26
        相关资源
        最近更新 更多