-
Notifications
You must be signed in to change notification settings - Fork 16
A Simple Template Filter
Writing filters is very simple to do and an easy way to extend the behavior of your templates. They consist of a function & the registration of that function as a filter. Let's dive in.
We'll create a filter that allows us to pull out the hostname of a url, turning https://example.com:8000/blog/2012/01/18/test-post
into just example.com
. Put the following code somewhere in your page:
<script type="text/javascript" src="/js/plate.min.js">
<script type="text/javascript">
var hostname = function(url) {
var anchor = document.createElement('a');
anchor.href = url;
return anchor.hostname
};
plate.Template.Meta.registerFilter('hostname', hostname);
</script>
The hostname
function itself is pretty straightforward. Pay special attention to accepting a callback
first in the arguments. You then do whatever processing is needed. Finally, you end the function by calling the callback
, passing it err, data
arguments.
You then register the filter with Plate. The first argument you provide is the name the filter will be available as. The second is the actual function the filter is implemented in, by convention the same name but not required to be.
Finally, you can use filter in your template like Posted on {{ entry.url|hostname }}.