Описание


Утилита pghtml рекурсивно сканирует указанную директорию, при обнаружении файлов с расширениями .pg* (настраивиается) счытывает их, проводит в них замены (см. ниже) и сохраняет в одноименные файлы, убрав из расширения префикс pg. Т.е. в файле example.pghtml будут проведены замены и он будет сохранен в файл example.html.

Обычно используется одним из трех способов в зависимости от конфигурации серверов

Вызов происходит по расписанию из планировщика заданий cron под пользователем postgres. В любом случае утилита pghtml сравнивает содержимое существующего файла с новым и, если содержимое файлов не изменились, то файлы не перезаписываются и redeploy не происходит.


Тег <pghtml-sql>

Синтаксис
<pghtml-sql>[SQL query]</pghtml-sql>

Действие
Содержимое тега выполняется как SQL запрос, полученный из базы данных результат подставляется вместо тега в результирующий файл


Пример
<pghtml-sql>
select now() - pg_postmaster_start_time()
</pghtml-sql>

<pghtml-sql>
select datname from pg_database order by 1
</pghtml-sql>

<a href="<pghtml-sql>select 'http://mysite/'||'${directory}'</pghtml-sql>">Page</a>

<pghtml-sql>
select json_agg(t) from (
  select schemaname "schema",indexrelname "index",idx_scan scans 
    from pg_catalog.pg_stat_all_indexes
    order by idx_scan desc limit 5
) t
</pghtml-sql>





37 days 21:19:21.25639


postgres
template0
template1


<a href="http://mysite/example/">Page</a>

[{"schema":"pg_catalog","index":"pg_proc_oid_index","scans":361}, 
 {"schema":"pg_catalog","index":"pg_proc_proname_args_nsp_index","scans":345}, 
 {"schema":"pg_catalog","index":"pg_attribute_relid_attnum_index","scans":198}, 
 {"schema":"pg_catalog","index":"pg_class_oid_index","scans":196}, 
 {"schema":"pg_catalog","index":"pg_cast_source_target_index","scans":120}]



Тег <pghtml-include>

Синтаксис
<pghtml-include [var_name]="[var_value]">[/][path/][filename]</pghtml-include>

Действие
Содержимое тега обрабатывается как путь к файлу, который вычитывается и подставляется вместо тега. Атрибуты тега преобразовываются в переменные. Если путь к файлу начинается с косой черты "/", то местоположение файла берется от директории, которая передана параметром при вызове утилиты (обычно это корневая директория сайта). В противном случае - от местоположения обрабатываемого (исходного) файла. Вложенность включений поддерживается вне зависимости от расширения.

Пример
<!-- inclusion of styles for acceleration -->
<style type="text/css">
<pghtml-include>/css/common.css</pghtml-include>
</style>

<!-- inclusion of title with two variables "G_SITE" and "description" -->
<pghtml-include description="Example">title.html</pghtml-include>


--
file title.html: 
<title>${G_SITE} | ${description}</title>





<!-- inclusion of styles for acceleration -->
<style type="text/css">
html {
  font: 12px Verdana, Arial, Helvetica, sans-serif;
}

p {
  font-size: 16px; font-weight: bold;
}
</style>

<!-- inclusion of title with two variables "G_SITE" and "description" -->
<title>PGHtml | Example</title>
                     



Переменная ${variable}

Синтаксис

${[name]}


Действие
Переменные заменяются своими значениями и задаются одним из четырех способов:
  • содержимое элемента <pghtml-var name="var_name">[var_value]</pghtml-var>
  • параметры -G_[name] [value] в командной строке при вызове утилиты
  • атрибуты тега <pghtml-include "var_name"="[var_value]">
  • встроенные переменные
    ${directory_root}
    ${directory}
    ${filename}
    ${filepath_source}
    ${filepath_dest}
    -
    -
    -
    -
    -
    корневая директория обработки, переданная в командной строке
    директория обрабатываемого файла
    обрабатываемый файл
    абсолютный путь до исходного файла
    абсолютный путь до результирующего файла

Пример
<!-- built-in variables -->
directory_root   = ${directory_root}
directory        = ${directory}
filename         = ${filename}
filepath_source  = ${filepath_source}
filepath_dest    = ${filepath_dest}

<!-- multiline variable -->
<pghtml-var name="text">
Line 1
<br>
Line 2
</pghtml-var>

text:
${text}

<!-- using variable "directory" in SQL query -->
length(directory) = <pghtml-sql>select length('$[directory]')</pghtml-sql>

<!-- inclusion of title with two variables "G_SITE" and "description" -->
<pghtml-include description="Example">title.html</pghtml-include>

--
file title.html: 
<title>${G_SITE} | ${description}</title>







<!-- built-in variables -->
directory_root   = /mysite/
directory        = static/
filename         = example.pghtml
filepath_source  = /mysite/static/example.pghtml
filepath_dest    = /mysite/static/example.html
                 
<!-- multiline variable -->
text:

Line 1
<br>
Line 2

<!-- using variable "directory" in SQL query -->
length(directory) = 7

<!-- inclusion of title with two variables "G_SITE" and "description" -->
<title>PGHtml | Example</title>                     



Командная строка

Параметры командной строки (после установки их можно посмотреть запустив pghtml --help)
[root@pgsuite ~]# pghtml --help
PGHtml is HTML template engine using PostgreSQL
version 24.2.7, linux 64 bits

Usage:
  pghtml {COMMAND} [OPTIONS]

Commands:
  start        start execution in another process
  execute      execute in current process
  status       show runtime status
  stop         stop execution
  sync         only synchronize directory and exit (some options are ignored)
  help|man     print this help

HTTP options:
  -hd DIRECTORY       site directory (default: /site)
  -hi INTERVAL        synchronization interval in seconds (default: 600)
  -hp PORT            HTTP port (default: 5480)

Connection options:
  -h HOSTNAME        database server host (default: server IP address)
  -p PORT            database server port (default: 5432)
  -d DBNAME          database name (default: site)
  -U USERNAME        username for service only (default: postgres)
  -W PASSWORD        password of user for service (if nessesary)

Logging options:
  -l  FILE           log file

Examples:
  pghtml start -d sitedb -l /var/log/pghtml.log
  pghtml execute -hd /mysite -h server-db.mycompany.com -d sitedb -U admin -W 12345
  pghtml sync -hd /site/db -d sitedb