Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 8 down vote accepted

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 + "')");
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.