【发布时间】:2019-09-02 02:16:25
【问题描述】:
我有一组模板,其中包含用 %%key%% 表示的关键短语(如果有问题,可以使用不同的分隔符)。 In the code presented, the names of the templates are shown in a selector, and when selected, their values are presently being moved into a textarea for display.在它们显示之前,我希望浏览模板并将每个键替换为与该键关联的值。
我尝试过使用 template.gsub 'key' 'value',template.gsub! 'key' 'value',甚至template['key'] = 'value',都无济于事。为了消除其他问题,我尝试对“值”使用简单的值,然后在警报中显示结果。如果我不尝试替换,警报会显示模板。如果我尝试这些尝试中的任何一种,我想我不会显示警报,表明某种 javascript 错误。我无法弄清楚错误是什么。
这是 application_helper.rb 的一部分:
#----------------------------------------------------------------------------
def render_haml(haml, locals = {})
Haml::Engine.new(haml.strip_heredoc, format: :html5).render(self, locals)
end
#----------------------------------------------------------------------------
def create_template_selector
get_templates()
render_haml <<-HAML
%select{{name: "msg", id: "template_selector"}}
- @t_hash.each do |name,message|
%option{ :value => message }= name
HAML
end
#----------------------------------------------------------------------------
def get_templates()
templates = Template.all
@t_hash = Hash.new
templates.each do |t|
@t_hash[t.name] = t.message
end
end
这是视图部分 _text.html.haml,其中嵌入了选择器,并在更改时显示其选择:
= form_for(@comment, remote: true, html: {id: "#{id_prefix}_new_comment"}) do |f|
= hidden_field_tag "comment[commentable_id]", commentable.id, id: "#{id_prefix}_comment_commentable_id"
= hidden_field_tag "comment[commentable_type]", class_name.classify, id: "#{id_prefix}_comment_commentable_type"
%div
%h3 Select a Template
= create_template_selector
%div
= f.text_area :comment, id: "#{id_prefix}_comment_comment", name:"text_msg"
.buttons
= image_tag("loading.gif", size: :thumb, class: "spinner", style: "display: none;")
= f.submit t(:add_note), id: "#{id_prefix}_comment_submit"
#{t :or}
= link_to(t(:cancel), '#', class: 'cancel')
:javascript
$(document).ready( function() {
$('#template_selector').change(function() {
var data= $('select').find('option:selected').val();
//
// Here is where I put alert(data) and it works
// but,
// var filled = data.gsub '%%first_name%%' 'Ralph'
// followed by alert(filled), shows no alert panel and no error
//
$("##{id_prefix}_comment_comment").val(data);
});
} );
How can I create a set of fill_ins like:
def fill_ins()
@fillins = Hash.new
@fillins['%%first_name%%'] = 'Ralph'
@fillins['%%last_name%%'] = 'Jones'
...
end
并创建一个类似的函数:
def fill_in(template)
@fi = fill_ins()
@fi.each do 'fkey, fval'
template.gsub! fkey fval
end
end
它工作了吗?
【问题讨论】:
标签: javascript ruby haml