I created an html helper
Html.BreadCrumb(IDictionary<string, string> crumbs)
Where the first string is the label and the second string is the URL.
The helper creates the html required (an unordered list, some classes for first element, current element, last element, dead element and separators etc)
All working nice, but I do this by creating a stringbuilder, pumping all the html in it and returning the stringbuilder's content as a string.
I figure in this example it doesn't matter all that much, but what if an Html helper is churning out a big load of html? Isn't there a way to push it to Response.Write instead of a stringbuilder?
Or any other issues/improvements you have?
BTW we have a naming pattern in ASP.NET MVC for the various rendering techniques.
Helpers that return a string of what they are should be named what they are. For example, Url.Action() and Html.TextBox() return those exact items. Thus, these helpers should be used with the <%= %> syntax.
Helpers that render directly to the output stream should start with Render. For example, Html.RenderPartial(). These are used with the <% %> syntax.
Helpers that use the IDisposable pattern should be named with Begin/End. For example, Html.BeginForm() and Html.EndForm(). These should also be used with the <% %> syntax.
Thanks,
Eilon
It certainly is possible to use Response.Write instead of returning a string; see the source for System.Web.Mvc.Ajax.Form (in AjaxExtensions.cs) in the MVC source for an example.
You then call the helper with <% instead of <%=.
Will it be any faster? I doubt it, but it's easy to test.
I don't think you will have any performance problems as long as the size of the HTML pages you produce is reasonable. And when you really start to create pages of megabytes in size, then you should ask yourself, why are you creating such huge HTML files?
Related
I have this code in my html.erb at many places.
<div id="left-nav">
<%= render :partial => 'tests/tests_left_menu' %>
</div>
Is it a good idea to create helper method for this type of code ?
How to write this code in helper ?
I see a few good strategies to use in your situation. Pick and choose based on your project's specific requirements.
You can just put div#left-nav and its contents into yet another partial like tests/tests_left_menu_with_wrapper. This saves you a couple of lines.
If you can generalize the cases when the entire segment appears, you can move it into a layout. This way, once you declare the layout for a particular action using the ActionController::Base.layout method, you'll be able to skip writing the entire segment altogether.
You can write a helper, but it's not clear what advantage it confers over simply using content_tag. You're probably better off using partials or layouts.
Personally i don't think there's a need to, and i think it's more like because you are not using other tools like haml to help reduce the number of lines in an erb files
the same code can be achieved in haml in just 1 line:
#left-nav= render :partial => 'tests/tests_left_menu'
hope this helps =)
I suppose if you have that code in many places I'd move the the div into the partial. If you need the flexibility to have tests_left_menu outside of the div I'd still pick two partials over a helper in this scenario. Avoid writing html in Ruby when you can :)
I often see, touted as one of the big benefits of ASP.NET MVC, the fact that it gets you closer to the actual page markup, as opposed to the pseudomarkup of WebForms.
If that's the case, then why does the HtmlHelper exist? It seems like all this LabelFor, TextBoxFor stuff is just as much pseudomarkup as <asp:Label> and <asp:TextBox> are in WebForms.
What am I missing? Why is there an HtmlHelper class? Do people use it in real life?
Whilst you are right in saying that HtmlHelper functions do abstract away the exact markup rendered, the big advantage of this is that the views are more DRY and you are able to pass in the necessary parameters to the functions in order to customise the HTML generated.
Rather than having to manually type out a full <input /> tag, complete with value=<%= Model.Property %>, Html.TextBoxFor is a more concise way of outputting the same thing. And as with all DRY approaches, if you need to change the HTML for all textboxes in your application (e.g. to output a new attribute) all you need to do is change the HtmlHelper method.
They seem to me a little like simple, lightweight partial views that are just designed to output some consistent HTML given some input.
The point of HTML helpers is to eliminate tedious and repetitive <input> tags.
Unlike server-side controls, HTML helpers emit raw, (fairly-)predictable HTML.
It simplifies the creation of those and allows them to be strongly named. Of course people use this!
I don't quite agree with the answers, and i somehow agree with you.
You can think of the helpers as pre-built custom controls, if you want to have some code generated you can make use of the helpers, if you want a clean approach and get closer to the html then don't.
The important point here is that MVC allows you to get close to the html, but does not limit you to only that.
You can create your own helper that created the markup you wish, and use that instead.
At the end of the day, it comes down to your own preference, and you can choose to or choose not to be closer to the html
I know that <%: does the html.encode thing, but there are lots of situations when I'm sure that I don't need to encode, so why should I waste time on encoding stuff that I'm 100% sure it doesn't require to be encoded like for example <%:Url.Action("Index") %> or <%: Model.Id %> (is of type int)?
The : code nugget is part of the ASP.NET 4.0 web compiler and doesn't just call Html.Encode(). It works out whether or not the string is already encoded first (if the expression returns an IHtmlString then it probably won't get encoded).
This means it is safe to use it when inserting actual data or when inserting HTML from some type of helper method (if you write your own helper methods, they should always return IHtmlString as of MVC 2).
With regards to whether or not you always use it, of course you don't. But I'd rather not think about it too much and will be happier knowing I've gone some way towards fending off XSS attacks with little effort; therefore, I nearly always use it.
It also encourages you to make sure you return a MvcHtmlString from your HTML helper methods rather than a string.
One example where you would not want to use <%: is for strings that come from your resource file that include HTML escape characters. I don't think you can make a blanket statement that you should always use <%:.
Personally I use it only for stuff that I know that needs to be encoded. No need to use it for integer types <%: Model.Id %> but that's just a personal preference.
<%: model %> is equivalent of <%= Html.Encode(model)%>
using <%: saves keystrokes and improves your productivity,
but sometimes you will have a need to do <%= (not to encode whatever you are displaying on your page)
One of the advantages of encoding to HTML is that it makes the pages W3C Valid according to corresponding datatype. So why validate the document in the first place?
For the answer to that please check, please check: http://validator.w3.org/docs/why.html
Briefly validating HTML saves a lot of time later in the development cycle and its a good practice.
Its easier, if you use only one type, and makes the code more clean.
also, you never know, who will change the code, and makes out of a simple "100 %" statement, a not so 100% statement :-)
Normally, in a web environment, the performance on such things are not an issue.
i would suggest to only use "<%:" as a team development guideline. just to be on the safe side.
When using ActionLink to render data from database which has HTML tags
(ie <p>)
incorporated in it, ActionLink escapes the tags. What is the best way to handle this?
In valid (X)HTML, paragraph tags are disallowed inside of anchor tags, so I wouldn't expect the framework to allow it.
I don't know that you can turn off the XSS protection in the helper methods, but you can always build your own helper methods. Just make an extension method that hangs off the Html class.
If you just want to render some HTML from the database, you can use <%= ViewData["MyContent"] %> if you're controller loads the data into the MyContent view data. Just know that you have to clean this HTML yourself.
I have heard that it's best not to actually have any html in your helpers; my question is, Why not? And furthermore, if you were trying to generate an html list or something like that, how can I avoid actual tags?
Thanks!
-fREW
My advice - if it's small pieces of HTML (a couple of tags) don't worry about it. More than that - think about partials (as pulling strings of html together in a helper is a pain that's what the views are good at).
I regularly include HTML in my helpers (either directly or through calls to Rails methods like link_to). My world has not come crashing down around me. In fact I'd to so far as to say my code is very clean, maintainable and understandable because of it.
Only last night I wrote a link_to_user helper to spits out html with normal link to the user along with the user's icon next to it. I could have done it in a partial, but I think link_to_user is a much cleaner way to handle it.
I don't see that there's anything wrong with it. The majority of the rails helpers generate HTML code (which is their purpose) - to me this implies that's what you're supposed to do yourself.
There is however the ever-present issue of code readability. If you have a helper which just builds a big string of raw HTML, then it's going to be hard to understand. While it's fine to generate HTML in helpers, you should do it using things like content_tag, and render :partial rather than just return %Q(<a href="#{something}">#{text}>)
This isn't a full answer to your question, but you can create html in your tags via the content_tag method. My guess as to why would be cleanliness of code.
Also, content_tag allows you to nest tags in blocks. Check out this blog post on content_tag.
On Rails 3 you can use *html_safe* String method to make your helper methods return html tags that won't be escaped.
As mentioned before, helpers are generally thought to be used as business logic, for doing something that drives view code, but is not view code itself. The most conventional place to put things that generate snippets of view code is a partial. Partials can call a helper if needed, but for the sake of keeping things separated, it's best to keep business in the helper and view in the partial.
Also, bear in mind this is all convention, not hard and fast rules. If there's a good reason to break the convention, do what works best.
I put html into partials usually.
Think about semantics. If you put html in a string, you lose the semantic aspect of it: it becomes a string instead of markup. Very different. For example, you cannot validate a string, but you can validate markup.
The reason I wanna put html in a helper instead of partial (and how I found this thread) is terseness. I would like to be able to write =hr instead of =render 'hr'.
To answer the question I didn't ask ;-) : to un-escape HTML in a helper, try this
def hr
raw '<hr />'
end