TwigJS - markhowellsmead/helpers GitHub Wiki

I had problems with the implementation of TwigJS in spring 2018, but I can't remember what they were…

jQuery alternative to TwigJS replace

WordPress REST API data

JavaScript

The data construct in this example is specifically for results from the WordPress REST API.

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};

var card_template = $('[data-post-template]').html();

var hasFeaturedMedia = function(post){
	if(!post.hasOwnProperty('featured_media')){
		return false;
	}
	if(!post.featured_media.hasOwnProperty('sizes')){
		return false;
	}
	if(!post.featured_media.sizes.hasOwnProperty('large')){
		return false;
	}
	return true;
};

$.each(posts, function() {
	resultCards += card_template.replaceAll('{{ data.id }}', this.id)
		.replaceAll('{{ data.date }}', this.date_legible)
		.replaceAll('{{ data.link }}', this.link)
		.replaceAll('{{ data.title }}', this.title.rendered)
		.replaceAll('{{ data.preview }}', this.excerpt && this.excerpt.rendered ? this.excerpt.rendered : '')
		.replaceAll('{{ data.image_src }}', hasFeaturedMedia(this) ? this.featured_media.sizes.large : '');
});

HTML

This is raw HTML, not for use in a Twig file. If you want to put this in a Twig file, wrap it with {% raw %} and {% endraw %} so that the Twig parser doesn't try to parse it!

<script type="text/template" data-post-template>
	<article class="post post-{{ data.ID }}">
		<div class="card-section with--padding">
			<time class="post-date">{{ data.date }}</time>
			<h2 class="post-title">
				<a rel="bookmark" href="{{ data.link }}">{{ data.title }}</a>
			</h2>
			<p class="post-preview">{{ data.preview }}</p>
			<p class="more">
				<a class="more-link" rel="bookmark" href="{{ data.link }}">More</a>
			</p>
		</div>
		<a rel="bookmark" class="flood" href="{{ data.link }}"></a>
	</article>
</script>

Feronia search machine

The principle is the same as for the WordPress REST API. Only the data construct is different.

$.each(response.data, function() {
	$resultContainer.append(result_template.replaceAll('{{ data.title }}', this.title)
		.replaceAll('{{ data.content_description }}', this.content_description)
		.replaceAll('{{ data.digest }}', this.digest)
		.replaceAll('{{ data.link }}', this.url_link)
		.replaceAll('{{ data.more }}', superSearchStrings.more));
});
⚠️ **GitHub.com Fallback** ⚠️