Mustache: Retrieve list/hash of tags from a template?

懵懂的女人 提交于 2019-12-07 19:23:38

问题


All the documentation and examples of Mustache I've seen show how to use a hash to populate a template. I'm interested in going the other direction. EG, if I have this:

Hello {{name}}

Can mustache generate this (pseudo-code):

tags = 'name'

I'm using the PHP flavor of Mustache, but I'm not too particular about the language. What I'm trying to do is build a system where people can create templates with Mustache tags, and another developer can quickly see what data the template will need. Is this something Mustache can do, or am I going to have to do some fun regex magic?


回答1:


You could use Hogan.js running on nodejs for example, and use the scan function:

var template = "{{foo}}{{#bar}}{{baz}}{{/bar}}{{#array}}{{.}}{{/array}}"'

var parsedTree = Hogan.scan(template, '{{ }}'​)​​​​;

What this returns is an array of objects. Each object entry has two keys that you want to look for: n represents the tag name, tag represents the tag type. I don't think the tag types are clearly documented, but as a reference _v means plain text, # is a section start and / is section end.




回答2:


I know I'm late to this question but I stumbled upon it when looking for a recommendation on how to do the same thing, in Ruby. Since I found a solution that's working well for me, I thought I would share:

Create a custom renderer, subclassed from Mustache, and track the requests for each partial or context there. You're going to want/need the normal rendering behavior anyway, since you'll want to catch contexts/partials referenced from other partials.

In Ruby, this is really easy to do -- hope it's still helpful for the PHP devs out there, too. :)



来源:https://stackoverflow.com/questions/9355364/mustache-retrieve-list-hash-of-tags-from-a-template

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