How to render HTML inside Slim templates

2019-03-24 16:18发布

I'm trying to render a link preceded by an icon. I'm using Slim templating engine along with Bootstrap CSS.

Usually you could do this the following way:

<a href="#"><i class="icon-user"></i> My Profile</a>

According to Slim's documentation, we can use == to render without escaping HTML. So, translating this to Slim, I tried the following variations:

li== link_to "<i class='icon-user'></i> My Profile", current_user
li== link_to "#{'<i class="icon-user"></i>'.html_safe} My Profile", current_user
li= link_to "#{'<i class="icon-user"></i>'.html_safe} My Profile", current_user

All variations rendered <a href="/users/1"><i class="icon-user"></i> My Profile</a> escaping the i tag.

How can I stop Slim or Rails from escaping html?

(Rails 3.2 with Slim 1.2.1)

4条回答
孤傲高冷的网名
2楼-- · 2019-03-24 17:19

This has been answered, but if you actually have some html and you want to render it in a slim template, use double equal.

== "<i>test</i>"

Will be the same as

= "<i>test</i>".html_safe
查看更多
孤傲高冷的网名
3楼-- · 2019-03-24 17:21

Alternatively, you could write this as

li
  a href=url_for(current_user)
    i.icon-user My Profile

which arguably is a little easier to read.

查看更多
Ridiculous、
4楼-- · 2019-03-24 17:25

You want to disable HTML escaping for the link_to argument, not the entire link_to result. You're pretty close with your html_safe but your string interpolation is eating your "safe for HTML" flag. This should work better:

li= link_to '<i class="icon-user"></i> My Profile'.html_safe, current_user
查看更多
戒情不戒烟
5楼-- · 2019-03-24 17:25

There's another way of tackling this below in case it helps anyone. Using a block is especially useful if you have more complex code to include within the link.

li
  = link_to current_user do
    i.icon-user>
    | My Profile
查看更多
登录 后发表回答