How can I handle hash keys containing illegal identifier characters in Template Toolkit?

我的梦境 提交于 2019-12-01 13:54:02

问题


In Template Toolkit, if I have the following variable containing a hashref:

[% 
   artist = {
     'life-span' => '1975 to 1987',
   }
%]

What is the best way to output the data in 'life-span'?

I have tried...

[% artist.life-span %]

^This fails because of the hyphen.

[% artist.'life-span' %]

^This fails because the syntax is incorrect.

[% lifespan = 'life-span' %]
[% artist.$lifespan %]

^This works, but is impractical in a large app with lots of data.

Is there a better way?

The project I'm working on is a Catalyst based web app and the data comes from a number of different external web services, so I do not control the name of the hash keys. I guess I could pre-process the data in Perl, renaming the problem hash keys before giving it to TT, but that seems like a pretty crappy work-around.


回答1:


You can use the item vmethod: [% artist.item('life-span') %].



来源:https://stackoverflow.com/questions/2311303/how-can-i-handle-hash-keys-containing-illegal-identifier-characters-in-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!