使用哈希值渲染ERB模板 [英] Render an ERB template with values from a hash
问题描述
我必须在这里忽略一些非常简单的内容,但似乎无法弄清楚如何使用哈希映射中的值呈现简单的ERB模板。
I must be overlooking something very simple here but I can't seem to figure out how to render a simple ERB template with values from a hash-map.
我对红宝石比较陌生,来自python。我有一个ERB模板(不是HTML),我需要使用要从从外部来源接收的哈希映射中获取的上下文进行渲染。
I am relatively new to ruby, coming from python. I have an ERB template (not HTML), which I need rendered with context that's to be taken from a hash-map, which I receive from an external source.
但是ERB的文档指出, ERB.result
方法采用绑定
。我了解到它们是将变量上下文保存在ruby中的东西(类似于 locals()
和 globals()
python,我猜想?)。但是,我不知道如何从哈希映射中构建绑定对象。
However, the documentation of ERB, states that the ERB.result
method takes a binding
. I learnt that they are something that hold the variable contexts in ruby (something like locals()
and globals()
in python, I presume?). But, I don't know how I can build a binding object out of my hash-map.
一点点(实际上是 ),谷歌搜索给了我这个: http:/ /refactormycode.com/codes/281-given-a-hash-of-variables-render-an-erb-template ,它使用了一些红宝石元编程魔术,使我逃脱了。
A little (a lot, actually) googling gave me this: http://refactormycode.com/codes/281-given-a-hash-of-variables-render-an-erb-template, which uses some ruby metaprogramming magic that escapes me.
那么,对这个问题没有简单的解决方案吗?还是有更好的模板引擎(不与HTML绑定)更适合于此? (我之所以选择ERB,是因为它在stdlib中)。
So, isn't there a simple solution to this problem? Or is there a better templating engine (not tied to HTML) better suited for this? (I only chose ERB because its in the stdlib).
推荐答案
我不知道这是否可以视为更优雅是否:
I don't know if this qualifies as "more elegant" or not:
require 'erb'
require 'ostruct'
class ErbalT < OpenStruct
def render(template)
ERB.new(template).result(binding)
end
end
et = ErbalT.new({ :first => 'Mislav', 'last' => 'Marohnic' })
puts et.render('Name: <%= first %> <%= last %>')
或者通过类方法:
class ErbalT < OpenStruct
def self.render_from_hash(t, h)
ErbalT.new(h).render(t)
end
def render(template)
ERB.new(template).result(binding)
end
end
template = 'Name: <%= first %> <%= last %>'
vars = { :first => 'Mislav', 'last' => 'Marohnic' }
puts ErbalT::render_from_hash(template, vars)
(ErbalT has Erb,T为模板,听起来像凉茶。很难命名。)
(ErbalT has Erb, T for template, and sounds like "herbal tea". Naming things is hard.)
这篇关于使用哈希值渲染ERB模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!