Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newbie: ternary "if" condition syntax on VIEW

I would like to have the if condition logic like:

var == 10 ? “10″ : “Not 10″

on Rails VIEW. What I tried is following:

<%= session[:id]=="out"? link_to "Sign in", login_path : link_to "Sign out", logout_path%>

I know it looks odd, and unsurprisingly it does not work. So, if I would like to use ternary if condition on VIEW, what is the correct way to do in my case?

---------One more condition---------

I would like to have two "link_to" in else condition

-----The error message I got--------

compile error

syntax error, unexpected tSTRING_BEG, expecting kDO or '{' or '('
...ession[:id]=="out" ? link_to "Sign in",
like image 878
Leem.fin Avatar asked Oct 19 '11 08:10

Leem.fin


People also ask

How do you write ternary operator with if condition?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

What is conditional or ternary operator give syntax and example?

Since the Conditional Operator '?:' takes three operands to work, hence they are also called ternary operators. Working: Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then Expression2 will be executed and the result will be returned.

How do you write if Elseif and else in ternary operator?

The ternary operator, also known as the conditional operator, is used as shorthand for an if...else statement. A ternary operator is written with the syntax of a question mark ( ? ) followed by a colon ( : ), as demonstrated below. In the above statement, the condition is written first, followed by a ? .

Can we use ternary operator instead of if-else?

The conditional operator – also known as the ternary operator – is an alternative form of the if/else statement that helps you to write conditional code blocks in a more concise way.


2 Answers

Try this (the only diffrence is a space between " and ? and the use of parentheses)

<%= session[:id]=="out" ? link_to("Sign in", login_path) : link_to("Sign out", logout_path) %>

Altough parentheses are optional in Ruby they are needed to maintain operator precedence in some cases.

IMHO ternary operators are hard to read. You could also do something more verbose:

<%= link_to("Sign in", login_path) if session[:id] == "out" %>
<%= link_to("Sign out", logout_path) if session[:id] != "out" %>
like image 69
Matt Avatar answered Oct 06 '22 00:10

Matt


session[:id]=="out"?

looks wrong. It should be

session[:id]=="out" ?

By the way if you need more link in the else part switch to an if else. It could be more clean:

<% if condition %>
  link
<% else %>
  link
  link
<% end %>
like image 35
lucapette Avatar answered Oct 05 '22 23:10

lucapette