1

I always end up writing sth like this in my code:

function setSomeImage(image_name) {
$("#some_div").html("<%= image_tag ('image.png') %>");
}

I am setting images based on a variable that I pass and I have to use the image_tag helper to write it properly in rails. However, Javascript and the image_tag don't work together very well.

What I want to do is, I want to manipulate the image_tag filename dynamically with javascript.

I can now write sth like this:

function setSomeImage(image_name) {
$("#some_div").html('<img src="/assets/'+image_name+'.png">');
}

but that is not clean. I want to use the image_tag helper, sth like this:

function setSomeImage(image_name) {
$("#some_div").html('<%= image_tag ('+image_name+') %>');
}

but that's not working. Any idea how I could combine both? Is there any best practice doing this?

Another idea is to pass the image_path directly as a variable to the function but that is not always possible.

0

2 Answers 2

3

If your js file has extension of js.erb, you'll be able to use asset_path helper to display some asset but you won't be able to pass a js variable to it because first ruby part will be evaluated and during that time image_name, a js variable won't be present.

Sign up to request clarification or add additional context in comments.

Comments

0

image_tag is rendered by the rails application on the server so it is not possible to use it in JavaScript. The second code block that you thought was not clean is likely as good as you're going to get if you are trying to do this with JavaScript.

10 Comments

so you mean image_tag and other helpers used in a view are on the server? :)
That's what I'm saying :)
and js is not present on the server? It gets injected by browser?
Think of JS as completely different than what rails is doing. JS is only rendered in the browser. The ERB <%= image_tag ('+image_name+') %> is only something that rails is going to render in the HTML. The HTML that rails renders can be later manipulated by JavaScript, but you can not use rails view helpers in JavaScript.
|

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.