npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

templator-evgdudareff

v1.0.4

Published

A template engine for parsing HTML templates with dynamic syntax support. Supports variable interpolation, conditionals, loops, and event handlers.

Readme

Templator

Лёгкий шаблонизатор для обработки HTML-шаблонов с поддержкой динамического синтаксиса. Templator использует полную архитектуру компилятора (сканер → парсер → интерпретатор) для преобразования строк шаблонов в элементы DOM или HTML-строки.

Возможности

  • Интерполяция переменных: {{ variableName }} с поддержкой точечной нотации ({{ user.profile.name }})
  • Условный рендеринг: {% if condition %} ... {% else %} ... {% endif %}
  • Итерация по коллекциям: {% for item in collection %} ... {% endfor %}
  • Обработчики событий: @click="handlerName", @mouseover="handlerName" и т.д.
  • Множественные форматы вывода: рендеринг в элементы DOM или HTML-строки
  • Поддержка TypeScript: полностью типизирован с определениями TypeScript
  • Архитектура компилятора: чистое разделение ответственности между этапами сканера, парсера и интерпретатора

Установка

npm install templator-evgdudareff

Быстрый старт

Рендеринг в DOM (браузер)

import { Scanner, Parser, DomInterpreter } from 'templator';

const template = `
  {% for user in users %}
    <li @click="onUserClick">{{ user.name }}</li>
  {% endfor %}
`;

const scanner = new Scanner(template);
const tokens = scanner.startScan();
const parser = new Parser(tokens);
const ast = parser.parse();

const interpreter = new DomInterpreter(
  {
    users: [
      { name: 'Alice' },
      { name: 'Bob' }
    ]
  },
  {
    onUserClick: (event, context) => {
      console.log('User clicked:', event.target.textContent);
    }
  }
);

const domElement = ast[0].accept(interpreter);
document.getElementById('app').appendChild(domElement);

Рендеринг в строку (SSR/бэкенд)

import { Scanner, Parser, StringInterpreter } from 'templator';

const template = `
  <h1>{{ title }}</h1>
  {% if loggedIn %}
    <p>Welcome, {{ user.name }}!</p>
  {% else %}
    <p>Please log in</p>
  {% endif %}
`;

const scanner = new Scanner(template);
const tokens = scanner.startScan();
const parser = new Parser(tokens);
const ast = parser.parse();

const interpreter = new StringInterpreter({
  title: 'My App',
  loggedIn: true,
  user: { name: 'Alice' }
});

const html = ast[0].accept(interpreter);
console.log(html);
// Output: <h1>My App</h1><p>Welcome, Alice!</p>

Документация API

Scanner

Преобразует строки шаблонов в поток токенов.

const scanner = new Scanner(templateString);
const tokens = scanner.startScan();

Parser

Строит абстрактное синтаксическое дерево (AST) из токенов, используя рекурсивный спуск.

const parser = new Parser(tokens);
const ast = parser.parse(); // Returns Array<ExpVisitorInterface>

DomInterpreter

Преобразует AST в элементы DOM с подключением обработчиков событий.

const interpreter = new DomInterpreter(
  context,           // Data context: Record<string, unknown>
  handlers           // Event handlers: Record<string, (event: Event, context: any) => void>
);
const domElement = ast[0].accept(interpreter);

StringInterpreter

Преобразует AST в HTML-строку (игнорирует обработчики событий).

const interpreter = new StringInterpreter(context);
const html = ast[0].accept(interpreter);

Справка по синтаксису

Переменные

Получайте доступ к свойствам контекста с помощью точечной нотации:

{{ user }}
{{ user.name }}
{{ user.profile.email }}

Условия

{% if condition %}
  <p>Shown when true</p>
{% else %}
  <p>Shown when false</p>
{% endif %}

Циклы

{% for item in collection %}
  <li>{{ item.name }}</li>
{% endfor %}

Обработчики событий (только DOM)

Прикрепляйте обработчики событий к элементам:

<button @click="onButtonClick">Click me</button>
<input @input="onInputChange" />

Предоставляйте обработчики при создании DomInterpreter:

{
  onButtonClick: (event, context) => { /* ... */ },
  onInputChange: (event, context) => { /* ... */ }
}

Архитектура

Templator следует трёхэтапной архитектуре компилятора:

  1. Scanner (лексический анализ): преобразует строки шаблонов в токены
  2. Parser (синтаксический анализ): строит AST из токенов
  3. Interpreter (выполнение): проходит по AST с использованием паттерна visitor

Это чистое разделение даёт:

  • Множественные форматы вывода (DOM, строка и т.д.)
  • Простоту расширения для новых функций
  • Чёткую обработку ошибок на каждом этапе

Лицензия

MIT © e.dudarev