【问题标题】:Is there a way to display a substring with a different style than the string in the view in Rails?有没有办法在 Rails 的视图中显示与字符串不同样式的子字符串?
【发布时间】:2016-02-06 04:22:50
【问题描述】:

有没有办法指定记录的字符串属性中的一个词或一组词在视图中以不同的格式显示?

例如,如果我有一条使用以下命令创建的记录:

Place.new(name: "Taj Mahal", description: "Is an ivory-white marble mausoleum on the south bank of the Yamuna river in the Indian city of Agra.")

然后我在这样的视图中显示它(@place 保存由上一个命令产生的记录):

<p><%= "Place: " + @place.name %></p>
<p><%= "Description: " + @place.description %></p>

有没有办法做到这一点,例如ivory-white marble mausoleum的部分以不同的格式显示?

我在想,也许当我创建记录时,我可以放置一些特殊字符,也许可以以某种方式制作轨道来识别这些字符,以使其显示字符串的那部分具有不同的颜色或大小,但事实是我没有最微弱的想法如何做我想做的事......

有没有人能想到如何做到这一点?

【问题讨论】:

  • 添加记录时可以在&lt;b&gt;ivory-white marble mausoleum&lt;/b&gt;前添加html标签
  • 但是如果我这样做,我会在视图中看到:Is an &lt;b&gt; ivory-white marble mausoleum &lt;/b&gt; on the south bank of the Yamuna river in the Indian city of Agra.,你确定你可以这样做吗?

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

您可以添加自己的分隔符并执行以下操作:

控制器:

@place = Place.new(name: "Taj Mahal", description: "Is an ##ivory-white marble mausoleum## on the south bank of the Yamuna river in the Indian city of Agra.")

查看:

<p><%= "Description: " + @place.description.sub('##','<em>').sub('##','</em>').html_safe %> </p>

然后在 css 中执行以下操作:

em {
  color: blue;
  font-size: 43px;
  ...
}

【讨论】:

  • 我试过你说的,但我在视图中看到 标签是这样的:Is an &lt;em&gt; ivory-white marble mausoleum &lt;/em&gt; on the south bank of the Yamuna river in the Indian city of Agra. 并且没有应用 css,因为我猜标签被认为是字符串的一部分,你确定你能做到吗?
  • 这就是你想要的......然后你根据你的喜好来设计它们。您还可以将 换成另一个容器元素和类名,例如 等。
  • 我明白了...但它不起作用,例如:&lt;p&gt;Hi &lt;em&gt; How are you&lt;/em&gt;&lt;/p&gt; 就像你说的那样按预期工作,但 &lt;p&gt;&lt;%= "Hi &lt;em&gt; How are you&lt;/em&gt;" %&gt;&lt;/p&gt; 却没有。
  • 啊,你需要添加类似 html_safe 的内容以允许从变量呈现 html - 答案已更新
猜你喜欢
  • 2015-05-19
  • 2014-04-07
  • 1970-01-01
  • 1970-01-01
  • 2020-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-29
相关资源
最近更新 更多