How to write variable in haml - ruby-on-rails

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

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 create a strong element inside a p

In haml, how do I render the following incredibly basic HTML:
<p>Results found for <strong>search term</strong>
where 'search term' is actually a Ruby variable called #query?
I'm trying the following,
%p results found for <strong>= #query</strong>
But that renders = #query literally. If I try:
%p results found for <strong>
= #query
</strong>
then the query term renders correctly, but is on a new line.
Also, I'm wondering if there's a better way to render <strong> in haml, while keeping everything on the same line.
I'm aware of the haml documentation, but as far as I can see there isn't an example of using a simple inline Ruby variable.
-----UPDATE-------
The following code works, and shows how to use a variable that's not within tags:
%p
= #trials_found_count
results found for
%strong= #query
But I find it really unreadable - it's hard to tell that it renders as just one line of HTML without adding a comment above.
Is there a way I can put all this code on a single line? Or is this just how haml works?
HAML is whitespace delimited. Nested tags go on the line below and one level in from the tag above. Embedded Ruby from which you want to display output is opened with an '='. Embedded Ruby which you don't want to display such as the start of loops uses '-' These are equivalent to <%= %> and <% %> respectively in erb.
What you want would look like this:
%p
results found for
%strong= #query
Which would produce the html:
<p>results found for <strong>#query</strong></p>
It should be noted that the '=' to start Ruby evaluation can only come at the beginning of the line or after a tag declaration and that only one tag declaration can occur per line.
The Ruby Evaluation section of the reference you linked covers embedded Ruby in detail and the haml tutorial which covers embedded ruby and many other haml basics is here:
http://haml-lang.com/tutorial.html
Here's how I'd do it:
%p No results found for <strong>#{h #query}</strong>
I'm not sure, but you might need a non-breaking space to preserve the space between the for and the <strong>
%p results found for
%strong= #query

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

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.

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.

Using webrat's contain(text) matcher with haml

I'm using the following webrat matcher:
response.should contain(text)
With the following haml:
%p
You have
= current_user.credits
credits
I've written the cucumber step 'Then I should see "You have 10 credits"', which uses the webrat matcher above. The step fails, webrat does not find the text in the response because the haml actually produces
<p>You have
10
credits</p>
How can I get the matcher to match the output that haml produces?
Note: the above is a simplified example to the situation i'm dealing with. Writing the following haml is not an acceptable solution:
%p= "You have #{current_user.credits} credits"
You're right, this is a pain. I've found Webrat to be annoyingly touchy too much of the time.
Two ideas:
Fix your test. In this case you want it to be blind to newlines, so get rid of them all: response.tr("\n","").should contain(text)
Fix your Haml. This is probably the better option. You can use the multiline terminator | to tell Haml not to put line breaks in:
%p
You have |
= current_user.credits |
credits
See the Haml reference for more obscure stuff like this. (A surprising amount of which has to do with whitespace.)
Better than
%p= "You have #{current_user.credits} credits"
would be
%p You have #{current_user.credits} credits
since Haml automatically interpolates text nodes.
I've found that something like:
response.should contain(/You have 10 credits/m)
will often give me the match I want without me having to goof with my Haml. Given the choice between mucking with my markup, which I really want to be readable, and changing my matcher to a regular expression, the latter seems a small price to pay for the more straightforward coding of the view.
There are various facilities in Haml for manipulating whitespace, but the correct thing to do here is to either revise the matcher to be whitespace-independent or to use a filter for writing your inline content. For example:
%p
:plain
You have #{current_user.credits} credits
Or if you need more complex logic:
%p
:erb
You have <%= current_user.credits %> credits
Haml is designed for efficiently expressing the structure of a document, but it's not so good at expressing inline content. When you want to do fancy inline stuff (as here), it makes sense to drop into ERB/HTML rather than going purely Haml. For more details see this blog post.

Resources