Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render HTML inside Slim templates

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)

like image 258
Mohamad Avatar asked Jun 11 '12 22:06

Mohamad


People also ask

How to add Slim in html?

You can force Slim to add a trailing whitespace after a tag by adding a > . You can add a leading whitespace by adding < . You can also combine both.

What is Slim in html?

What's Slim? Slim is a page-templating language that minimizes markup and syntax. It removes most of the extra "programming-like" symbols from HTML so that your code looks cleaner. Slim also adds if-else statements, loops, includes, and more.

What is Ruby slim?

A lightweight templating engine for Ruby Slim is a Ruby template language whose goal is reduce the syntax to the essential parts without becoming cryptic. The initial design of Slim is what you see on the home page.


2 Answers

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
like image 102
nroose Avatar answered Oct 22 '22 09:10

nroose


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
like image 27
mu is too short Avatar answered Oct 22 '22 09:10

mu is too short