What is the meaning of “h” in “<%=h [ …] %>”?

前端 未结 6 1815
故里飘歌
故里飘歌 2020-12-24 05:00

When I generate a default scaffold, the display tags on show.html.erb have

<%=h @broker.name %>

I know the difference between &

6条回答
  •  眼角桃花
    2020-12-24 05:18

    Way late to the party but I'm adding a further explanation to what html_escape is doing to hopefully help other noobs like myself understand what's happening. Rails 3 and later automatically escape all output now and so there are much fewer situations where html_escape aka h() will be needed. The most notable of which is when you intend to use the html_safe method when building links with html in a presenter class etc. For example:

    #some_view.html.erb
    <%= @user.name %>  #This is 100% fine and will be automatically escaped by Rails 3+
    #Output =>  Brian Kunzig
    
    #Now say we want a link with html that we need preserved!  OMG WHAT ARE DO??
    <%=link_to "#{@user.name}".html_safe  #DANGER!!!
    

    The link above can cause serious problems and open you up to all sorts of xss (cross-site scripting) attacks. The most simple example, if a user saved their name as "" and you used html_safe on it, it will cause any page rendering their supposed name to get an alert saying 'omg'! This is a major problem. To avoid this do:

    <%=link_to "#{h(@user.name)}".html_safe #Winning!
    

    By escaping the potentially tainted data supplied by a user we're homefree!

提交回复
热议问题