Difference between <%= expression %> and <%= expression -%> on Ruby On Rails [duplicate] - ruby-on-rails

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Difference between -%> and %> in rails
I need to know what is the difference between <%= expression %> and <%= expression -%> on rails, please help me to make good foundation on Ruby On Rails

The '-%>' means, that no linebreak will be appended to the output of the expression. It's usefull if you want to control the amount of whitespace you have in the generated HTML but do not want to put all the code in a single line.

As mentioned before, the -%> is used to control output whitespace. I you're at all concerned with how your HTML looks, use HAML. HAML is way more clear and readable when coding and it generates clear, valid formatted HTML. No more forgotten close tags!

I say don't bother with '-%>' If you are using layouts and partials with your views it is difficult control the output anyway, things like indentation will likely be messed up. Just focus making your ERb look good and don't worry too much what the generated output looks like.

Related

Rails 4: how to insert line breaks in text_area?

I have created a blog in rails. I'm a beginner and got quite far, but now I'm stuck with a seemingly minor detail: I can't seem to format the posts (articles).
Here's the relevant part of my show.html.erb:
<p>
<strong>Content:</strong>
<%= simple_format (#article.content) %>
</p>
When I write something and insert html-tags, they are not recognized as such. What am I doing wrong?
Rails will automatically remove html tags to prevent someone from injecting code into your webpage (e.g. malicious javascript)
If your users cannot enter data into #article.content and it's always safe then you can flag it as safe usng the html_safe method.
<%= (simple_format (#article.content)).html_safe %>
Can you post the article content for reference? If I had to guess, I'd imagine Rails is escaping the html tags and inserting them as plain text (so the output looks like: Article content !
Take a look at Rails' helper methods like content_tag (http://apidock.com/rails/ActionView/Helpers/TagHelper/content_tag) and concat (http://apidock.com/rails/ActionView/Helpers/TextHelper/concat) and consider using those to help with generating the appropriate html tags.
An issue to be concerned with is who's going to be supplying the content. For example, if you're writing an application that other people will use, you want to make sure any html give you is escaped to avoid XSS attacks. In that case, you'll want to spend some time reading about how to properly sanitize user input.
You can now specify the tag it gets wrapped in (defaults to p) like so:
<%= simple_format (#article.content, {}, wrapper_tag: "div") %>
or
add white-space: pre-line style.
It will display \r or \n (enter) in user input as a new line.
for more info:
http://apidock.com/rails/v4.0.2/ActionView/Helpers/TextHelper/simple_format

How to write variable in haml

I'm trying to use haml on RoR.
I faced some problems in haml.
My sample code is below.
ERB:
<p> <div class="hello"> <%= #sample.val %> <%= #hogehoge.val %> </div> </p>
HAML:
%p
.hello
= #sample.val
= #hogehoge.val
I can write one line in erb file.
But, I have to write 4 lines in haml.
Haml is so smart and beautiful syntacx structure, isn't it?
But I think writing so many lines is not smart.
How do I write in one line in haml in this case.
If you don't like the way haml work, why do you use it? that's how haml work. If you want something different you need something different, there are more template languages.
You complain about the amount of line but think about the amount of characters and readability, maintainability. The amout of line is one of the less important things on your code, or do you write all your html code in one line when you use erb or plain html?
You could save a few line though doing:
%p
.hello= "#{#sample.val} #{#hogehoge.val}"
but is it really THAT important? Well, now you have 2 lines instead of 1, is it "smart" enough? I don't think you can have that in one line using haml.
But, I have to write 4 lines in haml.
Yes, but you've saved a lot of characters and now have compile-time errors if you don't get your nesting right. Don't focus on the lines used, but the clarity.
I think you can do this:
%p %div.hello
= #sample.val + " " + #hogehoge.val
.hello
= #sample.val
= #hogehoge.val
If you're using <p> for styling, you'd be better putting a margin property in your .hello css
You're missing the point of haml - it's less verbose than erb

erb, haml or slim: which one do you suggest? And why? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I am learning Rails and I have seen these template engines. I have no experience with them (only erb).
But as I am a beginner, I am really confused. Which one do you suggest and why? Erb, Haml or Slim? Please tell your reason for preferring one over the others. And if you have any other recommendations, please let us know.
EDIT:
I am NOT looking for a winner here. I just want to hear your opinions about them, their syntax, speed of execution, and so on.
Two big advantages of using slim over haml:
Slim is currently about eight times faster than haml.
Slim supports HTTP streaming, while HAML doesn't.
Slim has a more natural syntax: a href="foo.html"
ERB is good mainly if you have a web designer that will work on plain HTML and does not know either haml or slim. This way they can write HTML and you can embed ruby logic with the proper tags.
If you work on both HTML and ruby logic, or your designer is ready to learn something new (like HAML) I'd go for HAML. It is a lot more ruby-friendly, reduces char count by much and a lot more readable than ERB.
For example (taken from official HAML site):
In ERB your view will look like this:
<div id="profile">
<div class="left column">
<div id="date"><%= print_date %></div>
<div id="address"><%= current_user.address %></div>
</div>
<div class="right column">
<div id="email"><%= current_user.email %></div>
<div id="bio"><%= current_user.bio %></div>
</div>
</div>
While in HAML it will look like this:
#profile
.left.column
#date= print_date
#address= current_user.address
.right.column
#email= current_user.email
#bio= current_user.bio
A lot cleaner!
As for the difference between HAML and SLIM - I never really worked with SLIM but I guess it is a matter of taste - take a look at both syntaxes and decide which looks better in your eyes. I don't think there is a definite winner between those two (HAML/SLIM).
Off the top of my head this is what I came up with
ERB:
Pros
default out of the box
not white space dependent
lowest barrier of entry (if coming from HTML) as its HTML with Ruby code sprinkled in
most IDE's lexers read it by default
DHH prefers it
legacy apps are probably still using it
Cons
more verbose
content_for tags in helpers and views can get out of hand quickly
content_for tags makes nesting tags harder as erb only returns the last line in the block. so you have to append to a string and then return that.
HAML
Pros
more concise. no closing tags, fits in smaller screens
visually cleaner structure
has built in helpers (haml_concat, haml_capture) to utilize haml in helper methods
class chaining
lots of useful syntactic sugar like # for divs or . for class chaining, or :javascript for JS tags
Cons
whitespace dependent which makes for some hard errors to figure out at times
complex tags usually need to resort to "hash" format. (Although I actually think this is a great example of flexibility to someone starting out it could be a pain.)
added as a gem (again probably a stretch to put this as a con)
designers might have some trouble adjusting
in addition to the general whitespace warning... simple whitespace errors eg. tabs and spaces for indentation, can cause pages to err in production which normal specs/test won't catch. Moral: Expect greater need for view tests and possibly don't use haml for mission critical views, unless you're sure that your tests are testing the actual rendering of the view.
is slower (than erb)
caveat: this is ruby code we're talking about if speed is a blocking issue in your application there are alternatives to ruby, e.g. haskell
The question for me comes down to would you rather put % before every tag or | before every new block of text?
Slim:
tag(attr= "value")
| text
Haml:
%tag{attr: "value"}
text
One more thing to lookout for: haml assumes a white space between new lines (remove whitespace in haml) while slim assumes no space (Add whitespace in Slim here and here)
https://github.com/scalp42/hamlerbslim - is an independent benchmark which shows Slim and Erb as winners, performance wise (slim tends to reduce the HTML output size too.)
My personal opinion is that overall, Slim and Haml will save you time (== money) in terms of maintenance, providing you have Haml/Slim savvy people looking after your views.
If you don't have those people, Erb is definitely the way to go, because despite the best will in the world, there are a lot of very inexpensive people available who can work with HTML/Erb, but find Haml/Slim a complete mystery.
Best of all cases, train these people to use Slim or at least expose them to it, and keep the numbers of the ones who "get it."

Rails - Outputting content, sanitize or <%=h?

I recently made a small rails3 app to convert an old cms written in another language. After migrating the content I am having problems outputting content from the database.
The #content.desc field sometimes has html. Currently the only way I could get it to work was:
<%= sanitize content.desc %>
But is this the best way? When I use <%=h #content.desc %> I can see the html tags still. When I use <%= simple_format #content.desc %> I get wicked spacing.
Is there a definitive guide somewhere where I can see all of the options while outputting content? I've tried to search but can't turn anything up (rails newb, i know).
Any string not marked as "safe" will be HTML-escaped by default in Rails 3. Some methods, such as sanitize, h, link_to and many other helpers return safe strings, thus allowing them to be written literally. See this blog post for more info.
If you know for sure that the HTML contained in #content.desc is safe, you can mark it as such yourself like so: <%= #content.desc.html_safe %>.
Rails 3 has changed HTML sanitisation to be enabled by default. If you're sure that the string you're rendering is safe, you can use
<%= #content.desc.html_safe! %>
Unless I'm mistaken, you shouldn't have to sanitize the content before displaying it, as Rails 3 does that by default. More info here: http://yehudakatz.com/2010/02/01/safebuffers-and-rails-3-0/

Correct coding convention for embedded code on web page templates

I had come experience with PHP a time ago and now I'm learning to use Ruby on Rails. But one simple question bothered me in both these languages, so I think I can cross-post it to both tags.
As you know, one of the concepts there is that one can embed PHP or Ruby code into web page template. Then these statements are executed and result of its execution is inserted in certain places of the page, marked with "brackets" <%= ... %>.
Or... wait. We program Ruby/PHP, but not HTML. Maybe we should treat template as Ruby/PHP code, into which sometimes HTML markup is inserted? So the process is treated like that HTML are inserted into ruby code into the "brackets" %> ... <%.
These are two different approaches:
HTML page is the primary entity, and it is affected by code execution; or
code is the primary entity, and it is executed, while HTML snippets are inserted in certain places.
This philosophy leads to different possibilities in coding conventions: result of code execution influences the page If we adhere the first insight, then the code would look like this:
<p>
<% (1..10).foreach do |i| %>
Iteration number <strong><%= i %></strong>. <br/>
<% end %>
</p>
But if we stick to the second alternative, the code would be formatted like this:
<%
%><p><%
(1..10).foreach do |i|
%>Iteration number <strong><%
%><%= i %><%
%></strong>. <br/><%
end
%>
How should the concept of templates be construed? What concepts do you, way more experienced Web developers, account for the coding convention?
If this is in your View layer (and it should be), then the HTML is the primary entity. It's the most pertinent part of that layer -- marking up your data to display in meaningful ways to the user.
Even aside from that, your second example is nearly unreadable. I see what you're doing, but it took me a minute to wrap my brain around it. I've also never, ever seen View-layer code like your second example (and I would make it one of my priorities to change it wherever I saw it if it was in a project I was working on).
To be more concise: you're putting the emphasis on the wrong thing. In my opinion, readability trumps just about everything else. The coding style that produces the most readable code is therefore the most superior (ceteris paribus and YMMV, of course).
Maybe you should look into Haml? I don't know if there's a php equivalent, but as far as Rails goes, it's somewhere in between the two schemes. It's not quite code centric. But when used right, all the raw html is prepared programatically.
In short everything is considered text to be directly outputted, unless prefixed with either a %, - or =. Which translate to html-tag, ruby code that doesn't output. Ruby code that does output. Haml then uses whitespacing to nest things properly, much like python does. Raw html outputs untouched but using % to specify a tag handles closing tags.
Sample:
#outer-div
- #items.each do |i|
%span.item
= i
%br
Outputs
<div id="outer-div">
<span class="item">
item
</span>
<br>
</div>
See the haml tutorial for more information.
To answer the central question. The bulk of any page is going to be HTML or raw text. We reduce the bulk of that text with includes and helpers, but it's still there. If there were a truly code centered approach my use of it would depend on the ratio of program logic to html. Personally I'd rather go with the html centered approach.
If you are interested in a code-oriented view, this is something you might try implementing as a pure Ruby DSL:
tag :p, :class => 'iterations-container' do
(1..10).each do |i|
text "Iteration number "
tag :strong { text i }
text "."
tag :br
end
end
Or perhaps instead of tag :p do ... end, you may favor tag.p do ... end.
I recommend doing only very simple logic in your template files. That way designers who can edit HTML can easily edit even those files to alter the layout if need be.

Resources