Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I barely use them in my projects. Is this normal? If I need to return just one line of html, say an image tag for a gravatar, then a helper is great:
def gravatar_for(user, height=90, width=90, alt=user.name + "'s gravtatar")
gravatar_address = 'http://1.gravatar.com/avatar/'
clean_email = user.email.strip.downcase
hash = Digest::MD5.hexdigest(clean_email)
image_tag gravatar_address + hash, height: height, width: width, alt: alt
end
However, if I want to loop through some errors, and return html structure rather than a single line, it quickly gets difficult.
Is a good rule of thumb if you want to return one line of html then use a helper, else use a partial to return more complex html?
First of all, the question is opinion based. So, most likely it will be closed.
Here are several questions on similar subject:
DRYing rails view: partial vs helper
Why shouldn't Helpers have html in them?
Generally speaking, helper is just a way to
Have DRY views
Make clean views and controllers
Generally speaking you can DRY views by moving out some duplicated functionality to controllers. However, as result controllers got cluttered. So, the better way to keep view related helpers in helpers (vs controllers), which you already figure out.
Some Helpers don't touch HTML at all (as example, they may just provide some formatting of numbers etc) or they may generate just one tag (as in your example) or generate piece of HTML code. However, as soon as you are talking about some piece of HTML code, you rather use partials vs helper.
Related
This question already has answers here:
Rendering a Rails view to string for email
(4 answers)
Closed 8 years ago.
I need to get the HTML code of the current page in Rails.
In the controller's action I need a string with that HTML code, for example:
<html><head></head><body><p>Hello</p></body></html>
The problem looks easy, but I can't find the solution.
If you need to render the output of an action as a string:
html = render_to_string(...)
It generally takes the same options as render but gives you the result you can work with instead of sending it to the client.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I'm a relatively new Rails developer with a heavy Java/C# background and I'm trying to pass multiple time ranges from my view to my controller. For instance, the user could select the time range 9:00am to 11:00am as well as 2:00pm to 4:00pm. The first thing to came to mind was a list of times or a list of key value pairs so that I know when a time range starts and ends. I'm having trouble figuring out how to pass this information to my Rails controller though.
Is there an ideal Rails way of passing a list to a controller?
From Rails Guide http://guides.rubyonrails.org/action_controller_overview.html
request
GET /mytime?t[]=1&t[]=2&t[]=3
in view
<form method="GET" action="mytime">
<select multiple name="t[]">
<option value="1">1:00pm</option>
<option value="2">2:00pm</option>
<option value="3">3:00pm</option>
</select>
</form>
or
<form method="GET" action="mytime">
<input type="text" name="t[]">
<input type="hidden" name="t[]" value="11">
</form>
#in mytime_controller.rb
def index
params[:t] # return Array of values
end
You pass information from a view to a controller via http query string ('get') or form data ('post').
I would consider multi-select dropdown for this case.
Instead of dropdown i suggest you should create a cool for using some jquery plugin that will improve your application's user experience and yes create a rails form and submit it then you can have information in your controller.
Now is you are saving these selected time, that i think you should do then create a model if you haven't already and use form_for else your can use form_tag for your rails application.
Visit Here and find some time picker that suits you need.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
We can use <text> tag in Razor to print the text context in some Iteration or want to display some dynamic text.
Confusion
We can do the above without using the tag also.
Question
What is the basic benefit to use <text> that is not common while comparing with other techniques to display text?
Please let me know in case there is any problem in understanding the question.
The main benefit is to make your code clean, declarative and self-explanatory.
Also <text> tag can eliminate some inconveniences in HTML/C# context switching (without it you will be forced to use #: to indicate context switching).
So, <text> is more like a syntax sugar not some required thing.
Consider the following code snippet. It is invalid and you will end up with exception if try to run it.
#foreach (var item in Enumerable.Range(0, 10))
{
user
}
We have two options to deal with this issue. They are both valid but first seems to be more consistent and declarative.
#foreach (var item in Enumerable.Range(0, 10))
{
<text>user</text>
}
#foreach (var item in Enumerable.Range(0, 10))
{
#:user
}
#foreach (var item in Enumerable.Range(0, 10)) { user } - here, if you don't put the tag, compiler will assume the whole block is C#, try to find a variable user which does not exist, throws error. The tag is to say clearly that 'user' is just a text which we want in our html.
It can be done with <p>, <span> or any other existing html tag, but that will put each text in a paragraph (with extra spacing and all) or other markups - which you might not want. See, the point is, if you already have some html tag, compiler will understand that as html and treat properly. But, in cases like the example by #AlexK where you don't want extra html elements, just want to put some plain text - there you use to distinguish it from C# codes.
The first line in the other answer, you can do the same thing with #: instead of tag. They do the same thing, make C# compiler differentiate html from code block. looks more html-ish & is more handy in cases where you have multi-line text. Refer ScottGu's blog
Context switching here means going back and forth between C# code block and html markup while generating a razor view page. The code we write for asp.net mvc views are combination of C# and html codes e.g.
1. <ul>
2. #foreach (var p in persons)
3. {
4. <li>
5. #p.Name
6. details
7. </li>
8. }
9. </ul>
where line 1, 4, 7, 9 are html, 2, 3, 5, 8 are C# and line 6 is both. So while compiling, the compiler has to clearly understand what is code and what is markup! So, based on some symbols (# for code, tags for html etc) compiler goes back and forth from C3 to html and create a final html.
The unique thing about the <text> tag is, it is not a standard html element, but can be used in razor view in the same way. It just encloses a block of plain text that will be rendered in generated html without any html markup.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Just to help other developers, because there is no similar question on SO.
div class=(is_active? ? 'active' : 'inactive')
div class=('active' if is_active?)
See the examples below:
div class=(is_active? ? 'active' : 'inactive')
div class=('active' if is_active?)
The same approach can be used to assign dynamic values to other attributes.
I use array of classes and nil element if there is no need to include class in list, then compact array to remove nil elements and finally join all together.
div class=(["cday", "col-md-1", day.day == 1 ? "col-md-offset-#{day.cwday-1}" : nil].compact.join(' '))
If you have multiple conditions I am doing right now something like
div class=(('foo ' if is_foo?) + ('bar' if is_bar?))
Though I feel it to be a blemish if is_bar? return false and the generated HTML results in
<div class="foo "></div>
(the blemish is the blank character after the foo). If someone had a solution for that would be awesome.
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."