Chrome Mustache.js Render Templates

I want to add some HTML to some websites with the Chrome extension, and it would be much better to use a template system like Mustache.js to do this. However, I cannot figure out how to access the contents of the template file. An example of what I'm trying to do:

content_script.js

var image = chrome.extension.getURL('logo.jpg'); var tb = Mustache.to_html( chrome.extension.getURL('template.html'), { "imageURL": image, "num": 5 } ); $('body').prepend(tb); 

template.html

 <div id="topbar"> <img src="{{imageURL}}"></img> {{num}} </div> 

The image is displayed just fine, as you would expect. And so loading template.html just returns the following line: chrome-extension://badmldhplgbmcbkolbmkhbamjaanjejj/template.html

How to get the contents of my template file as a string?

Thanks to Boris Smus for solving

content_script.js

 var req = new XMLHttpRequest(); req.open("GET", chrome.extension.getURL('template.html'), true); req.onreadystatechange = function() { if (req.readyState == 4 && req.status == 200) { var image = chrome.extension.getURL('logo.jpg'); console.log('Rendering Mustache.js template...'); var tb = Mustache.to_html( req.responseText, { "imageURL": image, "num": 5 } ); $('body').prepend(tb); } }; req.send(null); 
+8
javascript google-chrome-extension mustache
source share
1 answer

chrome.extension.getURL(file) returns the absolute URL of the requested file, not its contents. You must do XHR on the template to get its contents.

Alternatively, save the contents of your template in your HTML using something like <script id="templ" type="text/x-template">...</script> , and then link to the template contents via document.getElementById('templ') .

+7
source share

All Articles