templates

package
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 25, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package templates provides a Jinja2-like template engine for markata-go.

The package wraps the pongo2 library, which implements Jinja2/Django-style template syntax in Go. It provides a template engine, context management, and custom filters for common operations.

Template Engine

The Engine type manages template loading, caching, and rendering:

engine, err := templates.NewEngine("templates/")
if err != nil {
    log.Fatal(err)
}

// Render a template file
html, err := engine.Render("post.html", ctx)

// Render a template string
html, err := engine.RenderString("{{ post.title }}", ctx)

Template Context

The Context type holds data available to templates:

ctx := templates.NewContext(post, articleHTML, config)
ctx.Set("custom_key", "custom_value")

Available variables in templates:

  • post: The current post object
  • body: Rendered article HTML
  • config: Site configuration
  • title, tags, slug, etc.: Shortcuts to post fields
  • site_title, site_url, etc.: Shortcuts to config fields

Template Syntax

The template syntax is compatible with Jinja2/Django:

Variables:      {{ post.title }}
Loops:          {% for tag in post.tags %}{{ tag }}{% endfor %}
Conditions:     {% if post.published %}...{% endif %}
Filters:        {{ post.title | upper }}
Blocks:         {% block content %}...{% endblock %}
Inheritance:    {% extends "base.html" %}
Includes:       {% include "partials/header.html" %}

Custom Filters

The package provides custom filters for common operations:

Date formatting:

  • rss_date: Format for RSS feeds (RFC1123Z)
  • atom_date: Format for Atom feeds (RFC3339)
  • date_format: Custom date format

String manipulation:

  • slugify: Convert to URL-safe slug
  • truncate: Truncate string with ellipsis
  • truncatewords: Truncate by word count
  • striptags: Remove HTML tags

Collections:

  • length: Length of string/slice
  • first/last: First/last element
  • join: Join with separator
  • reverse: Reverse string/slice
  • sort: Sort slice

Other:

  • default_if_none: Default value for nil/empty
  • urlencode: URL-encode string
  • absolute_url: Convert to absolute URL
  • linebreaks/linebreaksbr: Convert newlines to HTML

Example Templates

Base template (base.html):

<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}{{ site_title }}{% endblock %}</title>
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>

Post template (post.html):

{% extends "base.html" %}
{% block title %}{{ post.title }} | {{ site_title }}{% endblock %}
{% block content %}
<article>
    <h1>{{ post.title }}</h1>
    <time>{{ post.date | date_format:"January 2, 2006" }}</time>
    <div class="tags">
        {% for tag in post.tags %}
        <span class="tag">{{ tag }}</span>
        {% endfor %}
    </div>
    <div class="content">{{ body | safe }}</div>
</article>
{% endblock %}

Package templates provides a template engine for markata-go using pongo2 (Jinja2-like syntax).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Context

type Context struct {
	// Post is the current post being rendered
	Post *models.Post

	// Body is the rendered article HTML (markdown content converted to HTML)
	Body string

	// Config is the site configuration
	Config *models.Config

	// Feed is the feed being rendered (for feed templates)
	Feed *models.FeedConfig

	// FeedPage is the current page of paginated feed results
	FeedPage *models.FeedPage

	// Posts is the list of all posts (for index/archive templates)
	Posts []*models.Post

	// SidebarItems holds the resolved sidebar navigation items for the current page
	SidebarItems []models.SidebarNavItem

	// SidebarTitle holds the title for the current page's sidebar
	SidebarTitle string

	// Core provides access to the lifecycle manager for filter/map operations
	Core interface{}

	// Extra holds additional context values
	Extra map[string]interface{}
}

Context holds data available to templates during rendering.

func NewContext

func NewContext(post *models.Post, body string, config *models.Config) Context

NewContext creates a new template context with the given post, body, and config.

func NewFeedContext

func NewFeedContext(feed *models.FeedConfig, page *models.FeedPage, config *models.Config) Context

NewFeedContext creates a new template context for feed rendering.

func (Context) Clone

func (c Context) Clone() Context

Clone creates a copy of the context.

func (*Context) Get

func (c *Context) Get(key string) interface{}

Get retrieves an extra value from the context.

func (*Context) Merge

func (c *Context) Merge(other Context)

Merge merges another context into this one. Values from the other context override existing values.

func (*Context) Set

func (c *Context) Set(key string, value interface{})

Set sets an extra value in the context.

func (Context) ToPongo2

func (c Context) ToPongo2() pongo2.Context

ToPongo2 converts the Context to a pongo2.Context for template execution.

func (Context) WithCore

func (c Context) WithCore(core interface{}) Context

WithCore returns a copy of the context with the Core field set.

func (Context) WithPosts

func (c Context) WithPosts(posts []*models.Post) Context

WithPosts returns a copy of the context with the Posts field set.

func (Context) WithSidebar added in v0.4.0

func (c Context) WithSidebar(items []models.SidebarNavItem, title string) Context

WithSidebar returns a copy of the context with the SidebarItems and SidebarTitle fields set.

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine provides template rendering capabilities using pongo2.

func NewEngine

func NewEngine(templatesDir string) (*Engine, error)

NewEngine creates a new template engine with the given templates directory. The templates directory is used as the base path for template loading. If templatesDir is empty, templates can only be rendered from strings.

func NewEngineWithTheme

func NewEngineWithTheme(templatesDir, themeName string) (*Engine, error)

NewEngineWithTheme creates a new template engine with theme support.

func (*Engine) ClearCache

func (e *Engine) ClearCache()

ClearCache clears the template cache. This is useful during development when templates are being modified.

func (*Engine) Dir

func (e *Engine) Dir() string

Dir returns the templates directory path.

func (*Engine) FindTemplate

func (e *Engine) FindTemplate(name string) string

FindTemplate returns the full path to the template, searching through all paths. Returns empty string if not found in filesystem (embedded templates don't have paths).

func (*Engine) HasEmbeddedTemplate

func (e *Engine) HasEmbeddedTemplate(name string) bool

HasEmbeddedTemplate checks if a template exists in embedded templates.

func (*Engine) LoadTemplate

func (e *Engine) LoadTemplate(name string) (*pongo2.Template, error)

LoadTemplate loads and caches a template by name. The template is loaded from the search paths in order, with embedded templates as fallback.

func (*Engine) Render

func (e *Engine) Render(templateName string, ctx Context) (string, error)

Render renders a template file with the given context. templateName is the path relative to the templates directory.

func (*Engine) RenderString

func (e *Engine) RenderString(templateStr string, ctx Context) (string, error)

RenderString renders a template string with the given context. This is useful for inline templates in markdown content (jinja_md).

func (*Engine) RenderToString added in v0.5.0

func (e *Engine) RenderToString(templateName string, ctx map[string]interface{}) (string, error)

RenderToString renders a template by name with a raw map context. This is useful for rendering templates from plugins that don't use the full Context type. The ctx map is converted to a pongo2.Context for template execution.

func (*Engine) SearchPaths

func (e *Engine) SearchPaths() []string

SearchPaths returns the ordered list of template search paths.

func (*Engine) SetDir

func (e *Engine) SetDir(dir string) error

SetDir sets the templates directory and reinitializes the loader.

func (*Engine) SetTheme

func (e *Engine) SetTheme(themeName string)

SetTheme sets the theme and rebuilds search paths.

func (*Engine) TemplateExists

func (e *Engine) TemplateExists(name string) bool

TemplateExists checks if a template file exists in any search path or embedded templates.

func (*Engine) ThemeName

func (e *Engine) ThemeName() string

ThemeName returns the current theme name.

type TimeValue

type TimeValue struct {
	time.Time
}

TimeValue is a helper type to make time.Time work better in templates.

func (TimeValue) String

func (t TimeValue) String() string

String returns the time formatted as RFC3339.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL