如何在Ruby中使用ERB文件在文本文件中写入一些文本

问题描述 投票:0回答:1

我有一个play.erb文件:

<p>Welcome!<br><p>
<% if $wgplaying==true %>
        Template: <%= $template %>
<% end %>
<br><br>

<% if $wginword==true && $wgplaying==true && $a!='' %>
        Character <%= $a %> is in word.
<% end %>

<% if $wginword==false && $wgplaying==true && $a!='' %>
        Character <%= $a %> is not in word.
<% end %>   

<br><br>

我想写

"Character <%= $a %> is in word."

"Character <%= $a %> is not in word." 

在文本文件中,但是我不知道应该使用什么命令。还是应该在Ruby文件中执行此操作?

ruby erb
1个回答
2
投票

ERB在Ruby的标准库中,所以尝试这样的事情:

require 'erb'

TEMPLATE_FILE = 'template.erb'

$wgplaying = true
$template = "This is my template"
$wginword = true
$wgplaying = true
$a = "something"

render = ERB.new(File.read(TEMPLATE_FILE),trim_mode: ">")
puts render.result

new方法有很多选项。

这些是new选项:

trim_mode
© www.soinside.com 2019 - 2024. All rights reserved.