I am trying to change the approach of rendering templates. I was using a server-side template engine. Now that I need to return only JSON from backend instead of HTML, I need to move my templating to front-end.
The problem for me as a newbie, is when the template contains a form. In other words, when the final JSON should also contain a csrf token. Please to take the example of CRUD application for books (one entity Book(id_book, name)
). The template for Read
ing a record shows the book name and allow deletion of a book.
In Symfony2 controller, I use createFormBuilder()
method that creates the delete form object, to which I apply createView()
method. The object returned by the latter is used by form_widget()
in the template engine (Twig). At the end:
<div id="bookName">{{book.name}}</div>
<div id="bookDelete">
<form action="{{ path('book_delete', { 'id': book.id }) }}" method="post">
<input type="hidden" name="_method" value="DELETE" />
{{ form_widget(delete_form) }}
<button type="submit"></button>
</form>
</div>
Which will return:
<div id="bookName">Symfony2 In Depth</div>
<div id="bookDelete">
<form action="/web/app_dev.php/deletes" method="post">
<input type="hidden" name="_method" value="DELETE">
<div id="form">
<input type="hidden" id="form_id" name="form[id]" value="15">
<input type="hidden" id="form__token" name="form[_token]" value="dd6573ae916ae30f78ba35a8c67e5d42a2764c1c">
</div>
<button type="submit"></button>
</form>
What I imagine when moving template rendering to front-end is a final JSON from server looking like:
{
'id':15,
'name': 'Symfony2 in Depth',
'csrf_token' : 'dd6573ae916ae30f78ba35a8c67e5d42a2764c1c'
}
Question is how to implement the same Symfony2 internal mechanism to render csrf token for DELETE form, as part of the final JSON to read a book entity? Is it acceptable to get rid of {{ form_widget(delete_form) }}
and all its long objects, and only serialize csrf token with book name? What does this will affect? I feel it is good for performance but how?
Your usual guidance is much appreciated.