Matt
Matt

Reputation: 2070

What's the best way to use Symfony2 to serve AngularJS partials?

I'm not sure how I should be serving partials from Symfony to Angular.

I was thinking I should set up a route in Symfony, and then have the controller output the file?

I wasn't sure however how to simply output a file from the controller (i.e. no twig stuff, not really rendering anything, etc.) And will this method cache it properly?

For example,if I want angular to download partials/button.html, should I set up a route like:

partials:
    pattern:  /web/partials/{partial}
    defaults: { _controller: AcmeWebBundle:Partials:show, _format: html }

Then, in my controller have,

...
public function showAction() {
    return file_get_contents(' ... path to file ...');
}
....

That obviously doesn't work.. I'm not sure how to output just a straight file without going through twig. Or maybe all my partials should just be twig files (just without any twig stuff in them)?

Upvotes: 3

Views: 2039

Answers (1)

Chase
Chase

Reputation: 9362

If you wanted to return the contents like that you would need to add the contents of the file to the response body.

use Symfony\Component\HttpFoundation\Response;
...

public function showAction() {
    return new Response(file_get_contents(' ... path to file ...'),200);
}
...

But really you should just let your web server serve the file. What I do is put my partials in a sub folder under the web directory:

web/
     partials/
     img/
     js/
     css/

Then just call them domain.com/parials/partialFileName.html and because the file exists symfonys rewrites should ignore it by default and just serve the file.

Another method (mentioned here) is to put the files in your bundle's Resources/public folder, then run

php app/console assets:install --symlink

(where web is the actual directory web/)

This will generate symlinks in the web directory pointing to the public directories. So, if you have:

Acme/DemoBundle/Resources/public/partials/myPartial.html

it'll be available at:

http://www.mydomain.com/bundles/acmedemo/partials/myPartial.html

Upvotes: 8

Related Questions