slime-lang / slime

Minimalistic HTML templates for Elixir, inspired by Slim.
http://slime-lang.com
MIT License
371 stars 57 forks source link

How to use Elixir `case` expression #59

Closed lpil closed 7 years ago

lpil commented 8 years ago

Hello!

How does one use this expression in these templates?

maxneuvians commented 8 years ago

The workaround I came up with was moving the case statement into my phoenix view module and then invoking the function from the code. In this case I wanted to load a different layout based on the type of authenticated user.

ex:

defmodule SampleApp.LayoutView do
  use SampleApp.Web, :view

  def load_user_specific_layout(conn, module, template, assigns) do
    case conn.assigns[:current_user].__struct__ do
      SampleApp.Admin.Administrator ->
        render SampleApp.LayoutView, "admin.html", Map.merge(assigns, %{module: module, template: template})
      _ ->
        render module, template, assigns
    end
  end
end

and then in my .slim file I had:

body
    = if @conn.assigns[:current_user] do
      = load_user_specific_layout(@conn, @view_module, @view_template, assigns)
    - else
      = render @view_module, @view_template, assigns

Depending on your circumstances this may be preferred as you reduce the amount of logic in your templates. However, I can also think of times where you would want case just to be in the template.

lpil commented 8 years ago

Thanks Max :)

dannote commented 8 years ago

I faced this issue too recently.

smpallen99 commented 7 years ago

I have a use case where I would like support for this in the slim template. I'm working with dynamically generated templates and views for the new ExAdmin design and would prefer not to deal with adding a helper function in the view. Here is what I would like the syntax to look like:

- {action, name, path} = @action_path
- class = case action do
  - :new -> "fa fa-plus-square"
  - :edit -> "fa fa-edit"
  - :delete -> "fa fa-minus-square"
  - _ -> ""
li 
  = link to: path  do
    i class="#{class}"
    span = name

My work around is to use an eex template for this functionality.

Rakoth commented 7 years ago

Hi @smpallen99, You could use embedded elixir code block, like this:

elixir:
  class = case action do
    :new -> "fa fa-plus-square"
    :edit -> "fa fa-edit"
    :delete -> "fa fa-minus-square"
    _ -> ""
  end
i class=class