<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">#!/usr/bin/perl
# Define self-documenting templates as wiki pages without HTML::Template
# markup leaking into IkiWiki's output.
# Copyright Â© 2013-2014 Simon McVittie. GPL-2+, see debian/copyright
package IkiWiki::Plugin::templatebody;

use warnings;
use strict;
use IkiWiki 3.00;
use Encode;

sub import {
	hook(type =&gt; "getsetup", id =&gt; "templatebody", call =&gt; \&amp;getsetup);
	hook(type =&gt; "preprocess", id =&gt; "templatebody", call =&gt; \&amp;preprocess,
		scan =&gt; 1);
	hook(type =&gt; "readtemplate", id =&gt; "templatebody",
		call =&gt; \&amp;readtemplate);
}

sub getsetup () {
	return
		plugin =&gt; {
			safe =&gt; 1,
			rebuild =&gt; undef,
			section =&gt; "core",
		},
}

# This doesn't persist between runs: we're going to read and scan the
# template file regardless, so there's no point in saving it to the index.
# Example contents:
# ("templates/note" =&gt; "&lt;div class=\"notebox\"&gt;\n&lt;TMPL_VAR text&gt;\n&lt;/div&gt;")
my %templates;

sub preprocess (@) {
	my %params=@_;

	# [[!templatebody "&lt;div&gt;hello&lt;/div&gt;"]] results in
	# preprocess("&lt;div&gt;hello&lt;/div&gt;" =&gt; undef, page =&gt; ...)
	my $content = $_[0];
	if (length $_[1]) {
		error(gettext("first parameter must be the content"));
	}

	$templates{$params{page}} = $content;

	return "";
}

sub readtemplate {
	my %params = @_;
	my $tpage = $params{page};
	my $content = $params{content};
	my $filename = $params{filename};

	# pass-through if it's a .tmpl attachment or otherwise unsuitable
	return $content unless defined $tpage;
	return $content if $tpage =~ /\.tmpl$/;
	my $src = $pagesources{$tpage};
	return $content unless defined $src;
	return $content unless defined pagetype($src);

	# We might be using the template for [[!template]], which has to run
	# during the scan stage so that templates can include scannable
	# directives which are expanded in the resulting page. Calls to
	# IkiWiki::scan are in arbitrary order, so the template might
	# not have been scanned yet. Make sure.
	require IkiWiki::Render;
	IkiWiki::scan($src);

	# Having scanned it, we know whether it had a [[!templatebody]].
	if (exists $templates{$tpage}) {
		return $templates{$tpage};
	}

	# If not, return the whole thing. (Eventually, after implementing
	# a transition, this can become an error.)
	return $content;
}

1
</pre></body></html>