HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Linking to an image asset from a JavaScript file in Symfony 2

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
linkingassetimagefilejavascriptsymfonyfrom

Problem

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



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?

Solution

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

Code Snippets

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

Context

StackExchange Code Review Q#33134, answer score: 8

Revisions (0)

No revisions yet.