Search code examples
rubylistyamlhamlenumerable

Is it possible to pass a value to a YAML list?


I'm looking for a way to pass a value to a list enumerable, so I could produce a set of list items for a <ul>. The value should be displayed by the item that allows it.

  • new
  • favorites (15)           <-- 15 being the value I want displayed.
  • archived
  • deleted

The following does not work as is, but should help illustrate the goal to achieve.

HAML

%ul
  =list_of t('.menu', favorites_count: 15) do |item|
    #{item}

YAML

menu:
  - new
  - favorites ('%{favorites_count}')
  - archived
  - deleted

Note: initially I had my YAML include the <li> tags in a dictionary form, inside strings, one of which includes the count value. But I find it a bit clumsy to mix HTML and YAML, like so:

menu:
  first_item: <li>new</li>
  second_item: <li>favorites %{favorites_count}</li>
  third_item: <li>archived</li>
  fourth_item: <li>deleted</li>

Hence looking for a cleaner option, that will only render tags on the HAML side and not litter them in YAML.


Solution

  • I18n.t uses interpolation syntax very similar to sprintf's, which you can use to your advantage:

    %ul
      = list_of t(".item") do |item|
        = sprintf(item, favorites_count: 15)
    

    I'm not entirely sure that's the right Haml syntax, but you get the idea.