I'm basically trying to produce jQuery effects based on the data I am coming in with from the server. I've tried multiple methods but its not coming out correctly
:javascript
"#{if #user.nil?}"
$('#test-container').show();
"#{end}"
The contents of #{...} need to be a single expression, and is allowed to go over multiple lines. Inside #{...} you can use literal strings simply by quoting them, and you don’t need quotes around the whole thing.
:javascript
#{if #user.nil?
"$('#test-container').show();"
end}
In this case you can do it as a single line:
:javascript
#{"$('#test-container').show();" if #user.nil?}
In general you want to avoid complex multiline interpolated blocks like in the first example. If necessary you should look at creating helpers to keep your views simple and understandable.
Does this work?
- unless #user
:javascript
$('#test-container').show();
Related
I am working on a Rails application whose HAML templates frequently make use of a routine called sanitize. I have deduced from context that this routine sanitizes user-controlled HTML. Example:
# views/feed_items/_about.html.haml
%h3 Summary:
.description
= sanitize #feed_item.description
I want to make this routine add 'rel=nofollow' to all outbound links, in addition to what it's already doing. What is the most straightforward way to do that?
N.B. I am not having any luck finding the definition of this method, or the official configuration knobs for it. The vendor directory has two different HTML sanitizer gems in it and I can't even figure out which one is being used. This is a large, complicated web application that I did not write, and I barely understand Ruby, let alone all of Rails' extensions to it. Please assume I do not know any of the things that you think are obvious.
The sanitizer will strip out the rel tags if they exist.
I ran into a similar issue and added an additional helper method - clean_links to the ApplicationHelper module, and called it after sanitizing the content.
# application_helper.rb
def clean_links html
html.gsub!(/\\2')
html.html_safe
end
This method looks for all <a> tags, and adds rel="nofollow". The html_safe method is necessary or else the HTML will be displayed as a string (it's already been sanitized).
This solution treats all links equally, so if you only want this for links pointing outside the domain, you'll have to update the REGEX accordingly.
In your view: <%= clean_links sanitize(#something) %>
So, first the content is sanitized, then you add the rel="nofollow" tag before displaying the link.
Actually there's a built-in way:
sanitize "your input", scrubber: Loofah::Scrubbers::NoFollow.new
I am using slim for templating and ruby on rails(just started using them). The only problem I am facing is: there is no formatting for the html rendered. i.e no line breaks, no indentation.
I can understand it can be a little tricky for slim to render formatting intrinsically.
Is there anyway to render properly formatted html?
From the docs:
Slim::Engine.set_default_options pretty: true
or directly
Slim::Engine.default_options[:pretty] = true
To expand a bit, as #rubiii mentioned in the comments this is a feature of Slim. For the same reasons it's good practice to minify and compress Javascript and CSS in production Slim strips unecessary whitespace from the HTML it produces without this :pretty option set to true.
If you have some config/initializers/slim.rb file you can configure the :pretty option dynamically by checking the environment.
Slim::Engine.set_default_options pretty: Rails.env.development?
Otherwise you should set this option to true only in config/environments/development.rb, leaving it false in production.
Just add data-force-encoding="✓" attribute to the body tag. That will make Rails to send email as quoted printable (trick is to use UTF8 char in fact). See: https://github.com/slim-template/slim/issues/123
Is there anyway to render properly formatted html?
HTML can be 'properly formatted' technically speaking, without line breaks. Look into 'HTML validation' if you are curious.
As for Slim, line breaks are one of the few points you have to do some extra work. Where many people use the HTML <br> tag, I prefer using $/ which is the ruby variable corresponding to the local line seperator. I prefer this becasue the <br> element is outmoded and though slim doesn't produce any output rendering it, it's bad practice to use the actual tag. The line ending variable is also more famliar and reliable for me personally :)
Actually another great reason to use $/ is that it seamlessly fits into other ruby coding patterns and is more agnostic overall. Check out this template as an example.
I'm using escape_javascript to return a partial to the browser via ajax.
Something like:
$("#inject").html("<%=escape_javascript(render :partial =>"feed/index")%>");
Problem is escape_javascript ends up outputing all kinds of wasted space like
\n\n\n\n\n \n
Is there anyway in Rails to escape_javascript more efficiently? No need for \n or long gaps of spaces?
Thanks
There is no standard Rails way to do this. You could just remove it yourself before passing it to escape_javascript like this:
$("#inject").html("<%= escape_javascript((render :partial => 'feed/index').squeeze(" ").gsub(/[\n\t]/,'')) %>");
I'm sure there's a sweet regular expression that would do it better, but this will get pretty close and won't harm your HTML. The gsub will replace newlines and tabs with nothing. The squeeze method will replace multiple occurrences of spaces with just one space. You don't want to remove all spaces because they likely occur intentionally in your HTML.
I'm going to revive this thread since I believe there is a misconception here.
The escape_javascript method, which can also be shortened to j, should not display any escaped line breaks (\n) when used with jQuery's append, prepend, html or functions of the like.
The most likely situation is that your rendered partial "feed/index" has another partial within it that is being escaped as well. This means you are javascript escaping your line breaks twice, which causes them to get interpreted improperly.
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?
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