3

Is it possible to use a variable which is passed from controller to view in render parameters to be used in javascript and how to do it?

1
  • you need to be more specific Commented Sep 26, 2015 at 14:50

2 Answers 2

2

The variable passed from controllers can be used in javascript as following:

<script type="text/javascript">
   alert("<%= @var %>")
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

Another way you can use PhoenixGon it generates script tag with variables and additional methods for simplicity. It generate all stuff for you. You only need to use it from window.Gon or wundow.YouApplicationNamespace. And you don't need other rendering and data attributing in html.

In controller:

def index(conn, _params) do
  conn = put_gon(conn, :variable, :value)
  render conn, "index.html"
end

In js module or browser console:

window.Gon.getAsset('variable')
# => 'value'

It also keeps Mix.env for using in js.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.