I have a label tag, whose content is loaded from a en.yml file.
html.erb
<%=label_tag(:name, t(:name, scope:[:helpers, :form], name: person_name(person))).html_safe%>
person_name is a helper and outputs a string
persons_helper.rb
def person_name(person)
content_tag(:span,
formatted_name(person.name) || t("helpers.persons.default_name"),
class: 'name').html_safe
end
output string from the helper is passed on t method and concatenated as following
en.yml
name: "Person Name: (%{name})"
I want the output to be like
<label for="person">
Person Name:
<span class='name> John Doe </span>
</label>
but Instead I get
<label for="person">
Person Name:(<span class="name">John Doe</span>)
</label>
I understand that it got to do with html_safe, raw and escaping strings but I just could not get it to work!
Thanks!
It appears that the
I18n.tmethod does not return a SafeBuffer (i.e. an html_safe string). So you should call.html_safeon the output from this method.Note the
.html_safecall has been moved in one parenthesis from where you had it. This can also be made marginally easier to see by using the block form of thelabel_taghelper.Note: I also switched to the
"helpers.form.name"method of selecting the I18n translation in this example to further increase readability (but this may be just a personal preference -- so use your original style if you prefer!).Finally, for security purposes -- so that a user's name doesn't come through unescaped -- you should remove the
.html_safefrom yourperson_namehelper and add a stricthtml_escape(orsanitize) so that it looks like this:In this form, the
content_tagwill make sure everything ishtml_safeexcept for the content. Meaning that theperson.namewill come through as is and be escaped as needed. However, this is not needed if theformatted_namemethod returns an already escaped orhtml_safename. Basically the point is that you don't want to blindly mark strings ashtml_safewhen they come from user inputted values because you don't know if they contain script tags or what. Hopefully this didn't confuse. :) In general, only mark strings ashtml_safewhen you are 100% sure that they are actually always going to be safe (i.e. they come from within your system and not from user input of any sort).