Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Check if asset collection exists

Whats the correct way to check if an asset collection exists before attempting to output?

If, I have a "footer" collection and attempt to output in my main layout without adding assets it throws an exception. If I use $this->assets->get('footer'), it will throw an exception if not created. This is what i do for now, but seems wrong:

$this->assets->collection('footer');
echo $this->assets->outputJs('footer');


29.4k
Accepted
answer

this way:

if($this->assets->collection('footer')->count())
{
    echo $this->assets->outputJs('footer');
}


10.1k

Thanks! I didnt see the count method. That makes more sense semantically, even though calling collection('footer') implicitly creates a collection I think.

Just an interesting question: I added 3 JS files to the collection

// IndexController  indexAction
$this->assets->collection('footer')->addJs("file1.js")->addJs("file2.js")->addJs("file3.js");

but when i did

// views/index.volt
{{ assets.collection("footer").count() }}

or

// views/index.phtml
echo $this->assets->collection("footer")->count();

the result is always 2 ?!

Am I missing something or it is a bug?



5.9k

@Uros

It is not a bug. You probably don't have one of the files added with addJs on the filesystem.

edited May '16

@mraspor

Thanks for the help. I also thought that, but it is not the situation.

Actually, i realized that i was watching the wrong assets collection. In the problematic collection i have 2 addJs calls and 1 addInlineJs call. In my opinion count() should return 3 while it really returns 2?!

I'd appreciate help here. Thanks



5.9k

@Uros,

If you look at https://github.com/phalcon/cphalcon/blob/master/phalcon/assets/collection.zep

You will see that the count() method returns $this->_resources:

return count(this->_resources);

which is populated only by addCss and addJs methods.

addInlineJs and addInlineCss use this->_codes which is not returned by a count method.

So, yes, correct answer is 2 (as inline isn't counted by the count method).