我在Twig中将一些设置存储在数组中,我需要将它们存储到某个变量中,以便我可以打印它。我的数组包含一些数据属性,如:
{% set data = {
visible: { data: "data-visible-items", value: options.visible_items },
scroll: { data: "data-itemes-scroll", value: options.items_to_scroll },
speed: { data: "data-animation-speed", value: options.animation_speed },
infinite: { data: "data-infinite", value: options.infinite },
autoplay: { data: "data-autoplay", value: options.autoplay_enable },
interval: { data: "data-autoplay-interval", value: options.autoplay_interval },
hover: { data: "data-autoplay-hover", value: options.autoplay_hover },
} %}
简单地说我想将数组中的所有内容存储在一个变量中,在这个变量中需要像这样存储(分隔符是空格),例如:
data-visible-items="5" data-items-scroll="2" data-animation-speed="400" data-infinite="0" data-autoplay="1" data-autoplay-interval="3000" data-autoplay-hover="1"
所以,如果变量是例如属性,我只想打印它:
<div{{ attributes}}>
// Content
</div>
我写了这样的循环:
{% for item in data %}
{{ item.data }} {{ item.value }}
{% endfor %}
它将打印每个数据和值,但是如何以我上面描述的方式将其存储在变量中?
答案 0 :(得分:-1)
如果您想要转换该数组,可以使用Twig_Filter
或Twig_Function
http_build_query
PHP
$twig->addFunction(new Twig_SimpleFunction('http_build_query', http_build_query', ['is_safe' => [ 'html', ],]));
枝条
<div{{ http_build_query(attributes, '', ' ') }}>
PHP
$twig->addFilter(new Twig_SimpleFilter('build_attribute_list', function (array $array) {
$str = '';
foreach($array as $key => $val) $str .= ' '.$key.'="'.$val.'"';
return $str;
}, ['is_safe' => ['html'],]);
枝条
<div{{ attributes|build_attribute_list }}>
(编辑)毋庸置疑,您也可以将输出存储在变量中
{% set my_var = attributes|build_attribute_list %}
{{ my_var }}
答案 1 :(得分:-1)
如果要存储到变量中,可以执行以下操作:
{% for item in data %}
{% set myvar = item.data ~ ' ' ~ item.value %}
{% endfor %}