pepper
pepper

Reputation: 1772

Reactjs server side templates

I wonder is there a way to load a react component template from server?

When I worked with Vuejs or any other js-library I actually have to add code to a view and after it rendered by server javascript starts running and do the rest.

For instance, I can type something like this in a Symfony app to get localized string: {{ 'header.article_title'|trans }} and it were translated.

However, since templates are hardcoded into a reactjs-component I can not use php/symfony/twig functions anymore. So, I'm wondering if there a way to fetch template from a server like an AngularJS templateURL-option.

Upvotes: 1

Views: 299

Answers (1)

pepper
pepper

Reputation: 1772

Finally get how to do what I need.

I've realized that it is possible to not have actual file by URL. So, if I need a /react/component/Article.js it could be a URL to an action.

So, I've created a new bundle, add a controller and use one action with view for a single react-component.

The skeleton code looks like this:

/**
 * Class ComponentController
 * @package ReactjsBundle\Controller
 *
 * @Route("/react/component")
 */
class ComponentController extends Controller
{
    /**
     * @Route("/Article.js")
     */
    public function articleAction()
    {
        $resp = new Response();
        $resp->headers->set('Content-Type', 'text/javascript');

        return $this->render('ReactjsBundle:Component:article.html.twig', [], $resp);
    }
}

Upvotes: 1

Related Questions