nik7
nik7

Reputation: 3058

slim-lang's if-else nested code

I want to assign a css class to a part of HTML based on condition in slim-lang

I am doing the following

- if current_user
  .title
- else
  .title_else

Now how can i write the HTML that should be nested in the one of the class above? Do i need to write HTML in the both if condition and else condition ?

The reason is that the HTML that should be nested in one of the above class should be further intended rightwards. But if i intend it further right, it is including under else condition. How shoule i approach this now ?

Upvotes: 22

Views: 38117

Answers (3)

Tiago Franco
Tiago Franco

Reputation: 1016

Here's a one liner:

.thing class=(current_user ? 'large-menu' : 'medium-menu')
  h4 Same content, different class

Upvotes: 35

Craig Walker
Craig Walker

Reputation: 51727

Since you're just toggling between two attributes, Tiago Franco's answer is certainly sufficient for your purposes. However, there is another way that comes in handy.

You can use capture to render HTML to a local variable, and then embed that content inside whatever control structure you like. So, if your wrapping content was a bit more complex, you'd do this:

- shared_content = capture do
  div This is displayed regardless of the wrapper
- if current_user
  | You're logged in!
  .title
    = shared_content
- else
  | You're not logged in!
  .title_else
    = shared_content

I'll often use this to wrap content in a link if there's a URL available:

- image = capture do
  img src=image_url
- if url.blank?
  = image
- else
  a href=url = image  

Upvotes: 20

PhilG
PhilG

Reputation: 1323

1) Yes, you need to write HTML into both of the created divs since you want it to be different. If you didn't want it to be different there would be no need for an if statement!

2) I didn't really understand your point, but this code worked perfectly fine with me:

- if true
  .title
    h4 True is true!
- else
  .title_else
    h4 True is not true!

This code showed a div with a class of .title and a h4 with the text True is true! inside it.

EDIT: Okay now I see what you mean! It is NOT possible to do something like this because it won't render the h4!

- if true
  .title
- else
  .title_else

    h4 Same content, different class

I would recommend you to write a helper which allows you to render partials and then just render that partial from inside both conditions. This means you only have to write that one partial and call it twice.

- if true
  .title
    = render 'footer'
- else
  .title_else
    = render 'footer'

Upvotes: 3

Related Questions