Rails content_tag插入额外的“<”和“>”人物

时间:2011-01-23 21:22:33

标签: html ruby-on-rails ruby-on-rails-3

这样做时:

def user_log
    if logged_in? == false
        form_tag session_path, :id => "mform" do
            content_tag(:span, content_tag(text_field_tag :email, "email@domain.com"), :class => "memail")+
            content_tag(:span, content_tag(password_field_tag :password, "12345678912"), :class => "mpass")+
            content_tag(:span, content_tag(submit_tag 'Login'), :class => "mbutton")
        end
    else
        ...     
        end
    end
end

我明白了:

stack overflow doesn't let me post pictures

因为我不想要额外的“<”和“>”,我做错了什么?

编辑:作为额外信息,我的观点是:

<%= user_log %>

3 个答案:

答案 0 :(得分:3)

根本问题在于,当您不需要时,您将使用两次content_tag。 content_tag基本上会调用content_tag_string。这是content_tag_string的来源:

def content_tag_string(name, content, options, escape = true)
  tag_options = tag_options(options, escape) if options
  "<#{name}#{tag_options}>#{content}</#{name}>".html_safe
end

调用content_tag(text_field_tag :email, "email@domain.com")看起来像:

"<#{text_field_tag :email, "email@domain.com"}>"

和text_field_tag已生成完整的HTML标记(包含“&lt;”和“&gt;”)。

要摆脱额外的斜角括号,你需要做的就是省去第二个content_tag

content_tag(:span, text_field_tag(:email, "email@domain.com"), :class => "memail")+

答案 1 :(得分:0)

作为第一个猜测,我可能会尝试类似:

if logged_in? == false
  ...
else
  ...
end.html_safe

更新:好的,回到绘图板。

作为第二个猜测,试试这个。 (并注意content_tag的额外参数,这需要将哈希值放在显式{} ...)

def user_log
    if logged_in? == false
        form_tag session_path, :id => "mform" do
          (
            content_tag(:span, content_tag(text_field_tag :email, "email@domain.com"),   {:class => "memail"},   false)+
            content_tag(:span, content_tag(password_field_tag :password, "12345678912"), {:class => "mpass"},    false)+
            content_tag(:span, content_tag(submit_tag 'Login'),                          {:class => "mbutton"},  false)
          ).html_safe
        end
    else
        ...     
        end
    end
end

答案 2 :(得分:0)

虽然我没有在本地尝试过,但问题很可能是Rails是html逃避你方便的助手方法。要查看我是否正确,请尝试将其放在您的视图中:

<%= raw(user_log) %>

如果可行,您可以在帮助方法中抛出raw

def user_log
    if logged_in? == false
        raw(form_tag session_path, :id => "mform" do
            content_tag(:span, content_tag(text_field_tag :email, "email@domain.com"), :class => "memail")+
            content_tag(:span, content_tag(password_field_tag :password, "12345678912"), :class => "mpass")+
            content_tag(:span, content_tag(submit_tag 'Login'), :class => "mbutton")
        end)
    else
        ...     
    end
end

raw告诉Rails这段代码是安全的,不需要进行html转义。

相关问题