-1

I have the following code in my twig template to manipulate the database:

{%
    $tablename = $app['config']->get('general/database/prefix') . 'entries';
    $query = "UPDATE $tablename SET $views = ? WHERE id = ?";
    $views = record.views + 1;
    $stmt = $app['db']->prepare($query);
    $stmt->bindValue(1, $views);
    $stmt->bindValue(2, record.id);
    $res = $stmt->execute();
%}

I get the following errors , when i load the template in my browser:

Twig_Error_Syntax
Unexpected character "$" in "record.twig" at line 18.

Why am i getting this error ??

Alexander Solonik
  • 9,838
  • 18
  • 76
  • 174

2 Answers2

6

You can't write PHP code in Twig template. The {% ... %} tag allows you to execute Twig code, not PHP code. Anyway, you shouldn't acces your database from inside a template, it seems so WRONG.

If you really need to do something like that, you should write a Twig Extension and call it from inside your {% ... %} tag.

katchou
  • 71
  • 1
  • 4
  • that code is for testing and yes later it will be made into an extension ! so how exactly do i now execute the above code ? – Alexander Solonik Nov 17 '16 at 08:58
  • 1
    You are trying to take a shortcut that does not exist. If you want to build an extension you have to set up a bare-bones extension first and then develop in that extension. Twig is designed to _not_ allow any PHP in the templates – jadwigo Nov 17 '16 at 09:42
2

If you want to update records in the database you will have to create your own extension that handles a twig tag to initiate that.

Tips and information to get you started are available in the bolt documentation: https://docs.bolt.cm/3.2/extensions/basics/creating

jadwigo
  • 339
  • 1
  • 9