Does conditional render stop code execution?

In a controller I am conditionally rendering a form based on form data:

if x == false do
  changeset = Model.changeset(%Model{}, model_params)
  conn
  |> put_flash(:error, "Condition not met")
  |> render("new.html", changeset: changeset)
end

...
#additional logic

I notice that while the render does happen if the condition is met the flow still continues after the conditional statement. I know that this could be fixed with by an else statement but there is a long list of conditional checks that occur. I’m more curious about what is happening exactly. Is the render just taking some time to process? Does render not release control of the flow?

You’re probably expecting your controller function to return early once the render function is called. However, there is no such thing as early return in Elixir.

If you can shed more light into what you’re wanting to accomplish (or share more code), maybe we can suggest an alternative route (perhaps via pattern matching, guards or other control flow mechanisms).

1 Like

Hi @asnyder002, the whole question seems to be a bit off, because it’s treating the conn as if it is mutable. It also doesn’t early return, as @juhalehtonen notes.

2 Likes

Use cond do for list of conditional checks:

cond do
    !x ->
        ...
    some_other_condiditon ->
        ...
end

Ah you are correct. I assumed, for some reason, that early returns were a thing. This controller action has actually gotten out of hand over time and is due for a refactor. I was trying to short circuit the flow in hopes of avoiding nested conditional logic.

1 Like

Well they can kind of be via a chunked response, but you’d have to split it up yourself and determine what to send when, but chunked responses is how you can do it (basically you give it a function to call back and it calls it repeatedly until you report done, sending whatever you gave it each loop). However, EEx templates do not work that way naturally.