Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
nunjucks filter to add entities
env.addFilter('addEntities', function(body, entities) {
if (!(entities)) {
return body;
}
// This is very naive, should find a better way to parse this
var index_map = {}
$.each(entities.urls, function(i,entry) {
index_map[entry.indices[0]] = [entry.indices[1], function(text) {return "<a href='"+escapeHTML(entry.url)+"'>"+escapeHTML(text)+"</a>"}]
})
$.each(entities.hashtags, function(i,entry) {
index_map[entry.indices[0]] = [entry.indices[1], function(text) {return "<a href='/hashtag/"+escape(entry.hashtag)+"'>"+escapeHTML(text)+"</a>"}]
})
$.each(entities.user_mentions, function(i,entry) {
index_map[entry.indices[0]] = [entry.indices[1], function(text) {return "<a title='"+escapeHTML(entry.name)+"' href='/"+escapeHTML(entry.screen_name)+"'>"+escapeHTML(text)+"</a>"}]
})
var result = ""
var last_i = 0
var i = 0
// iterate through the string looking for matches in the index_map
for (i=0; i < body.length; ++i) {
var ind = index_map[i]
if (ind) {
var end = ind[0]
var func = ind[1]
if (i > last_i) {
result += escapeHTML(body.substring(last_i, i))
}
result += func(body.substring(i, end))
i = end - 1
last_i = end
}
}
if (i > last_i) {
result += escapeHTML(body.substring(last_i, i))
}
return result;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.