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?
1 Answer 1
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 + "')");
}