link_to image_tag 与 Rails 中的内部文本或 html
我想使用 Ruby on Rails link_to
和 image_tag
方法输出以下内容:
<a href="#">Lorem Ipsum <img src="/images/menu-arrow-down.gif"></a>
Rails 中的好方法是什么?
I want to output the following with Ruby on Rails link_to
and image_tag
methods:
<a href="#">Lorem Ipsum <img src="/images/menu-arrow-down.gif"></a>
What would be a good way in Rails?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
您可以使用块作为字符串插值的替代方案,并正确使用
html_safe
。例如:You can use blocks as an alternative to the string interpolation with correct usage
html_safe
. For example:或者更短的方法是
Or a shorter way is
为什么不直接使用链接和图像标签呢?
您也可以尝试上面完成的附加操作(
string + image_tag
),但如果其中之一变为nil
,则会抛出错误。使用插值,如果nil
,它只会显示一个空白图像(或字符串)。对于 Rails 3,您需要使用
html_safe
:Why not just use a link to and image tag?
You could also try the appending done above (
string + image_tag
), but it will throw an error if one of those things becomesnil
. Using interpolation, it will just show a blank image(or string) if it isnil
.For Rails 3, you will need to use
html_safe
:我似乎不知道如何向 @corroded 的答案添加评论。但是,如果您使用的是 Rails 3,他的答案将无法按预期工作。如何解决这个问题可能不是很明显,至少对我来说不是。我知道我需要添加 html_safe,但把它放在了错误的位置。回想起来,这是显而易见的,但我想我应该把它放在这里,以供其他像我这样犯“菜鸟”错误的人使用。
但要小心,如果您为“hiii”使用用户可分配变量,则需要先对其进行清理。
请注意,my_model.some_string 或 yourimagepath 为 nil 没有问题,因为 h() 和 image_tag() 在传递 nil 时都会返回字符串。
I cannot seem to figure out how to add a comment to @corroded's answer. However, if you are using Rails 3, his answer will not work as expected. It might not be immediately obvious how to fix this, at least it wasn't for me. I knew I needed to add html_safe, but put it in the wrong place. In retrospect, it was obvious, but I thought I would include it here for others like me who make the "rookie" mistake.
be careful though, if you are using a user assignable variable for "hiii" you need to sanitize it first.
Note that there is no issue with my_model.some_string or yourimagepath being nil because both h() and image_tag() return strings when passed nil.
我更喜欢 HAML 中的这种方法
I prefer this approach in HAML
这是使用 link_to 包含图像和带有文本的 mailto href(显示在图像旁边)的一种很酷的方法:
在视图中提供类似的内容(整个图像和文本成为 mailto href):
Here's a cool way to use a link_to to include an image, and a mailto href with Text (displayed next to the image):
Giving you something like this in your view (the entire image and text become an mailto href):
对我来说这工作得很好:
For me this worked just fine:
我发现这也有效。
i found out this also which worked.