You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Run this command to install the plugin in the same environment as Datasette:
$ pip install datasette-template-sql
Usage
This plugin makes a new function, sql(sql_query), available to your Datasette templates.
You can use it like this:
{%forrowinsql("select 1 + 1 as two, 2 * 4 as eight") %}{%forkeyinrow.keys() %}
{{ key }}: {{ row[key] }}<br>
{%endfor%}{%endfor%}
The plugin will execute SQL against the current database for the page in database.html, table.html and row.html templates. If a template does not have a current database (index.html for example) the query will execute against the first attached database.
Queries with arguments
You can construct a SQL query using ? or :name parameter syntax by passing a list or dictionary as a second argument:
{%forrowinsql("select distinct topic from til order by topic") %}
<h2>{{ row.topic }}</h2>
<ul>
{%fortilinsql("select * from til where topic = ?", [row.topic]) %}
<li><ahref="{{ til.url }}">{{ til.title }}</a> - {{ til.created[:10] }}</li>
{%endfor%}
</ul>
{%endfor%}
Here's the same example using the :topic style of parameters:
{%forrowinsql("select distinct topic from til order by topic") %}
<h2>{{ row.topic }}</h2>
<ul>
{%fortilinsql("select * from til where topic = :topic", {"topic": row.topic}) %}
<li><ahref="{{ til.url }}">{{ til.title }}</a> - {{ til.created[:10] }}</li>
{%endfor%}
</ul>
{%endfor%}
Querying a different database
You can pass an optional database= argument to specify a named database to use for the query. For example, if you have attached a news.db database you could use this:
{%forarticleinsql(
"select headline, date, summary from articles order by date desc limit 5",
database="news"
) %}
<h3>{{ article.headline }}</h2>
<pclass="date">{{ article.date }}</p>
<p>{{ article.summary }}</p>
{%endfor%}
About
Datasette plugin for executing SQL queries from templates