gpt4 book ai didi

html - 如何在 sinatra 字符串中放置 html 标签

转载 作者:太空宇宙 更新时间:2023-11-03 17:16:53 25 4
gpt4 key购买 nike

我刚启动 Sinatra 并尝试使用 h1 html 标签呈现名称,但它不起作用。虽然字符串没有 html 标签,但它也没有根据需要呈现 html 标签让我知道如何在 Sinatra

中处理它

我的代码-

get '/nesh' do
name = "Swapnesh"
"Hello <h1> #{name} </h1> Sinha"
end

最佳答案

您从 get '/nesh' 返回的字符串 block 正是将在 HTTP 请求中返回的内容,这就是为什么它不包含在 <html>...</html> 中的原因标签。如果你希望周围有标签,例如 <html> , <body>等,那么你应该创建一个 Sinatra view模板,并将您的 View 信息(例如 name )传递到 View 渲染器。

一个完整的例子可能是这样的:

app.rb:

set :views, settings.root + '/templates'

get '/nesh' do
name = "Swapnesh"
erb :hello, :locals => {:name => name}
end

templates/layout.erb:

<html>
<body>
<%= yield %>
</body>
</html>

templates/hello.rb:

<h1>Hello <%= name %> Sinha</h1>

注意我还使用了 Sinatra layout ,这是所有呈现操作的基本模板(除非选择退出)。

最后,您可以使用 named templates 在一个文件中实现它:

template :layout do
<<-EOF
<html>
<body>
<%= yield %>
</body>
</html>
EOF
end

template :hello do
"<h1>Hello <%= name %> Sinha</h1>"
end

get '/nesh' do
name = "Swapnesh"
erb :hello, :locals => {:name => name}
end

关于html - 如何在 sinatra 字符串中放置 html 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15187141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com