0

In PHP I can do this:

<div class="foo <?php if($a) echo "bar"; ?>">
<?php if ($b) echo "</div>"; ?>

It is incredibly convenient. I can break a string in any place, between any quotes, between any HTML symbols, just wherever I want.

And I need to implement the same in Ruby-HTML. I'm trying to port a PHP project to Ruby. I use the Slim template language. I tried this but it doesn't work, Slim throws errors:

<div class="foo
- if (x == 1)
  = bar
"></div>

For now with Slim I know only one way:

- if (a == true)
   <div class="foo"></div>
- else
   <div class="foo bar"></div>

Firstly, duplication. Secondly, my HTML-PHP part of code is quite complicated. It is with two loops (for loop and foreach loop inside it) and I use more than one such an embeds to add div's attributes according to conditions. And just cannot imagine how to implement it with Slim. It throws an error even for this, I cannot break long html string:

- if(i != 5)
  <div class="foo bar" 
  id="item_#{i}" 
  style="background-color:red;" 
  data-im="baz">
  </div>
- else

Does Slim allow to break strings with conditional ifs between quotes or element attributes? How to do it?

Tahazzot
  • 1,224
  • 6
  • 27
Green
  • 28,742
  • 61
  • 158
  • 247

1 Answers1

2

If you're using Rails, you're free to facilitate ActionView::Helpers this way:

= content_tag :li, class: ( a == true ? "foo bar" : "foo") do
  inside div

Elsewise you're free to create some helper method to cover this logic for you

Nevertheless it's considered ill practice to include much logic in a view. Consider using some Presenter pattern

edit.

Looking into some slim docs found you're able to achieve your goal this way

div.foo class="#{'bar' if a == true}"
  | Text inside div
xeromorph
  • 71
  • 1
  • 5