Php Symfony2:如何用全局细枝变量替换某个字符串?
我在config.yml中有以下内容Php Symfony2:如何用全局细枝变量替换某个字符串?,php,symfony,twig,Php,Symfony,Twig,我在config.yml中有以下内容 twig: globals: locale_list_sg: Singapore locale_list_cn: China 在我的小树枝模板中,我希望根据一个参数得到“Singpaore”和“China”的值。 因此,我像这样连接它们并显示: {{'locale_list_' ~ countryId}} 但是,上面的内容将显示locale\u list\u sg,而不是进入config.yml并提取值。据我所知,
twig:
globals:
locale_list_sg: Singapore
locale_list_cn: China
在我的小树枝模板中,我希望根据一个参数得到“Singpaore”和“China”的值。
因此,我像这样连接它们并显示:
{{'locale_list_' ~ countryId}}
但是,上面的内容将显示locale\u list\u sg,而不是进入config.yml并提取值。据我所知,Twig将字符串解释为字符串;它不能确定变量。。。这不是很好,而是一个解决办法(假设您有一组有限的配置选项,您不介意重新键入:
{{
('locale_list_' ~ countryId)|replace({
'locale_list_sg': locale_list_sg,
'locale_list_cn': locale_list_cn
})
}}
希望有帮助。使用更简单的方法: config.yml
twig:
globals:
locale_list:
sg: Singapore
cn: China
模板:
{{ locale_list[country_id] }}
你不应该把camelCase和under_score变量名混在一起。坚持一种代码风格。Twig默认使用下划线变量名。我喜欢这个答案。有一个问题,为什么在“sg”和“cn”之前有一个“-”,它在YAML中定义了一个数组。@nifr这不是等同于
-{sg:Singapore}
?这意味着locale\u list[country\u id]
将不起作用,因为索引将是0
,而不是sg
。问题表明{'locale\u list\u'~countryId}
解析为locale\u list\u sg
-这意味着locale\u list[country\u id]
将解析为locale\u list[/sg
。这是一个关联数组,所以这里的键不是整数而是字符串。或者你的问题是什么?数字索引数组的形式是['value1','value2']
,关联数组的形式是{'key':'value'}
@AdamElsodaney是正确的。通过Symfony的Yaml解析器运行的Yaml返回这个数组:数组([twig]=>Array([globals]=>Array([locale\u list]=>Array([0]=>Array([sg]=>Singapore)[1]=>Array([cn]=>China)))