Documentation
¶
Overview ¶
Package templates provides template engine functionality for markata-go.
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 ¶
- func BackgroundToMap(b *models.BackgroundConfig) map[string]interface{}
- func ClearAllCaches()
- func ClearConfigMapCache()
- func ClearPostMapCache()
- func FontToMap(f *models.FontConfig) map[string]interface{}
- func GetAssetHash(path string) (string, bool)
- func GetConfigMap(c *models.Config) map[string]interface{}
- func GetPostMap(p *models.Post) map[string]interface{}
- func InvalidatePost(p *models.Post)
- func PostMapCacheSize() int
- func PostsToMaps(posts []*models.Post) []map[string]interface{}
- func SetAssetHashes(hashes map[string]string)
- func SwitcherToMap(s *models.ThemeSwitcherConfig) map[string]interface{}
- func ThemeToMap(t *models.ThemeConfig) map[string]interface{}
- type ConfigMapCache
- type Context
- func (c Context) Clone() Context
- func (c *Context) Get(key string) interface{}
- func (c *Context) Merge(other Context)
- func (c *Context) Set(key string, value interface{})
- func (c Context) ToPongo2() pongo2.Context
- func (c Context) WithCore(core interface{}) Context
- func (c Context) WithPosts(posts []*models.Post) Context
- func (c Context) WithSidebar(items []models.SidebarNavItem, title string) Context
- type Engine
- func (e *Engine) ClearCache()
- func (e *Engine) Dir() string
- func (e *Engine) FindTemplate(name string) string
- func (e *Engine) HasEmbeddedTemplate(name string) bool
- func (e *Engine) LoadTemplate(name string) (*pongo2.Template, error)
- func (e *Engine) Render(templateName string, ctx Context) (string, error)
- func (e *Engine) RenderString(templateStr string, ctx Context) (string, error)
- func (e *Engine) RenderToString(templateName string, ctx map[string]interface{}) (string, error)
- func (e *Engine) SearchPaths() []string
- func (e *Engine) SetDir(dir string) error
- func (e *Engine) SetTheme(themeName string)
- func (e *Engine) TemplateExists(name string) bool
- func (e *Engine) ThemeName() string
- type PostMapCache
- type TimeValue
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BackgroundToMap ¶ added in v0.6.0
func BackgroundToMap(b *models.BackgroundConfig) map[string]interface{}
BackgroundToMap converts a BackgroundConfig to a map for template access. This is exported for use by plugins that need consistent background config rendering.
func ClearAllCaches ¶ added in v0.6.0
func ClearAllCaches()
ClearAllCaches clears all template caches. Call this at the start of each build.
func ClearConfigMapCache ¶ added in v0.6.0
func ClearConfigMapCache()
ClearConfigMapCache clears the global config map cache.
func ClearPostMapCache ¶ added in v0.6.0
func ClearPostMapCache()
ClearPostMapCache clears the global post map cache. This should be called at the start of each build to ensure fresh data.
func FontToMap ¶ added in v0.6.0
func FontToMap(f *models.FontConfig) map[string]interface{}
FontToMap converts a FontConfig to a map for template access. This is exported for use by plugins that need consistent font config rendering.
func GetAssetHash ¶ added in v0.7.0
GetAssetHash retrieves the hash for a given asset path.
func GetConfigMap ¶ added in v0.6.0
GetConfigMap returns the cached map for a config, or converts and caches it.
func GetPostMap ¶ added in v0.6.0
GetPostMap returns the cached map for a post, or converts and caches it. This is the primary entry point for getting post maps with caching.
func InvalidatePost ¶ added in v0.6.0
InvalidatePost removes a specific post from the global cache.
func PostMapCacheSize ¶ added in v0.6.0
func PostMapCacheSize() int
PostMapCacheSize returns the size of the global cache.
func PostsToMaps ¶ added in v0.6.0
PostsToMaps converts a slice of Posts to a slice of maps. Exported for use by plugins that need to add posts to template context.
func SetAssetHashes ¶ added in v0.7.0
SetAssetHashes merges new hashes into the global asset hash registry. This should be called before rendering templates that use theme_asset_hashed. Multiple plugins can call this to register their generated assets.
func SwitcherToMap ¶ added in v0.6.0
func SwitcherToMap(s *models.ThemeSwitcherConfig) map[string]interface{}
SwitcherToMap converts a ThemeSwitcherConfig to a map for template access. This is exported for use by plugins that need consistent switcher config rendering.
func ThemeToMap ¶ added in v0.6.0
func ThemeToMap(t *models.ThemeConfig) map[string]interface{}
ThemeToMap converts a ThemeConfig to a map for template access. This is exported for use by plugins that need consistent theme config rendering.
Types ¶
type ConfigMapCache ¶ added in v0.6.0
type ConfigMapCache struct {
// contains filtered or unexported fields
}
ConfigMapCache provides thread-safe caching for config-to-map conversions.
func (*ConfigMapCache) Clear ¶ added in v0.6.0
func (c *ConfigMapCache) Clear()
Clear clears the config cache.
func (*ConfigMapCache) GetOrCreate ¶ added in v0.6.0
func (c *ConfigMapCache) GetOrCreate(cfg *models.Config) map[string]interface{}
GetOrCreate returns a cached map for the config, or creates and caches one.
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 ¶
NewContext creates a new template context with the given post, body, and config.
func NewFeedContext ¶
NewFeedContext creates a new template context for feed rendering.
func (*Context) Merge ¶
Merge merges another context into this one. Values from the other context override existing values.
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 ¶
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 ¶
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) FindTemplate ¶
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 ¶
HasEmbeddedTemplate checks if a template exists in embedded templates.
func (*Engine) LoadTemplate ¶
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 ¶
Render renders a template file with the given context. templateName is the path relative to the templates directory.
func (*Engine) RenderString ¶
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
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 ¶
SearchPaths returns the ordered list of template search paths.
func (*Engine) TemplateExists ¶
TemplateExists checks if a template file exists in any search path or embedded templates.
type PostMapCache ¶ added in v0.6.0
type PostMapCache struct {
// contains filtered or unexported fields
}
PostMapCache provides thread-safe caching for post-to-map conversions. This dramatically reduces memory allocations and CPU time when the same posts are converted multiple times (e.g., in feed pages, templates).
func (*PostMapCache) Clear ¶ added in v0.6.0
func (c *PostMapCache) Clear()
Clear clears the entire cache. Call this between builds or when posts change.
func (*PostMapCache) GetOrCreate ¶ added in v0.6.0
func (c *PostMapCache) GetOrCreate(p *models.Post) map[string]interface{}
GetOrCreate returns a cached map for the post, or creates and caches one.
func (*PostMapCache) Invalidate ¶ added in v0.6.0
func (c *PostMapCache) Invalidate(p *models.Post)
Invalidate removes a specific post from the cache. Call this when a post is modified.
func (*PostMapCache) Size ¶ added in v0.6.0
func (c *PostMapCache) Size() int
Size returns the number of cached entries.