1

What I want to do is have one page that lists some data from my database (the data is separate from Bolt).

I've looked into extensions but I don't see any way to make a "page" as such, only create "snippets". But snippets don't display actually in the content area, you can only add them right after the <body> tag or in the <head>. Also it looks like they appear on every page, not on page.

Is it possible to run some custom PHP code on a page to fetch some data from a database and display it? Does anyone have a bare-bones example?

DisgruntledGoat
  • 70,219
  • 68
  • 205
  • 290

1 Answers1

5

This is the sort of thing that extensions are for, but snippets are not what you want.

Bolt is a Silex application and comes with a Doctrine DBAL provider, so you can just use $app['db'] to give you access to the \Doctrine\DBAL\Connection object that you can use to query your table, e.g.

    $resultArray = $this->app['db']->createQueryBuilder()
        ->select('*')
        ->from($tableName)
        ->where('my_column_1  = :my_column_value_1')
        ->andWhere('my_column_2  = :my_column_value_2')
        ->orderBy('my_column_3', 'DESC')
        ->setParameter(':my_column_value_1', $value1)
        ->setParameter(':my_column_value_1', $value2)
        ->execute()
        ->fetch(\PDO::FETCH_ASSOC);

You can then do what you want with the data, and render that in Twig as you see fit.

There is a tonne of documentation on creating extensions with Twig functions that you can put in a template {{ my_twig_function() }}

Gawain
  • 1,568
  • 10
  • 8
  • OK I understand the database stuff and making a Twig function, but I'm still missing how it all fits together. Where do I call the Twig function from? Do I need to do something like `{% if page=='mypage' %} {{ my_twig_function() }} {% endif %}` in my page.twig? Seems a bit hacky to me to litter the template with that. – DisgruntledGoat Sep 11 '15 at 14:30
  • In the ContentType you use, you can specify a `templateselect` field type that will give you a select box to pick a template you want for that record. You just have a Twig file that inherits blocks from another template, but has your Twig function. – Gawain Sep 11 '15 at 15:20
  • Thanks! That also means I can just use the Twig function for retrieving the data only, and keep the actual HTML output in the template. – DisgruntledGoat Sep 11 '15 at 16:18