3
\$\begingroup\$

I am calling a JS file from a bundle directory like so:

<script src="{{ asset('bundles/macppages/js/main.js') }}"></script>

which loads the JS file into the base.index.twig

In that JS file I want to add some custom css via jQuery like this:

function loadBkrndImg(){
 var img = new Image(); 
 img.src = "/bundles/macppages/images/bkrnd.0" + currentBkrndImgNum + ".jpg";
 $('body').css("background-image","url('" + img.src + "')");
}

which works, but to the question:

Is this the correct way to do it using the Symfony 2 framework? In Symfony 1, there was a function you could call to pull the web dir. With Sym2, the assets are in the bundle directories, so is there a Symfony2 command for this so it is not so explicit?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Oct 23, 2013 at 17:51
\$\endgroup\$

1 Answer 1

8
\$\begingroup\$

There might be a better way to retrieve the web directory, I would not know. However, there are other things to ponder upon.

  • Naming : loadBkrndImg -> loadBackgroundImage looks so much better
  • Naming : currentBkrndImgNum, enough said..
  • The background image number ought to be a parameter to loadBackgroundImage, not a global
  • You are creating an Image() object, assign the src value ( which can trigger the loading of the image ) , and then throw away the image. You could just put the url in a string.
  • You could preemptively centralize the retrieval of the asset folder

I would counter-suggest the following :

function getAssetFolder( subfolder )
{
 var folder = '/bundles/macppages/';
 return subFolder ? ( folder + subfolder + "/" ) : folder
}
function loadBackgroundImage( number )
{
 var url = getAssetFolder( 'images' ) + 'bkrnd.0' + number + '.jpg';
 $('body').css("background-image","url('" + url + "')");
}
answered Jan 14, 2014 at 1:03
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.