Cobertos
Cobertos

Reputation: 2253

Tumblr theme getting tags of a post in JavaScript

I want to use the tags of a post in JavaScript. To get the tags I was originally using something like the following:

<article class="post" data-tags="{TagsAsClasses}">

This worked fine up until I needed to use special characters like | which becomes a _ with this property and gives me the wrong tag.

So now I need to do something like (using the {block:Tags}):

<article class="post" data-tags="{block:HasTags}{block:Tags}{Tag}{/block:Tags}{/block:HasTags}">

Yet I foresee problems if {Tag} ever has a double quote in it.

Is there any way I can keep the data-tags attribute and still use {block:Tags} to get the real tag?

I have come up with a solution that involves adding and then reading a bunch of markup but I just don't like it as much.

<div class="postHiddenTags" style="display:none;">
    {block:HasTags}
        {block:Tags}<div data-tag={JSTag} data-tagURL={JSTagURL}></div>{/block:Tags}
    {/block:HasTags}
</div>

Upvotes: 2

Views: 257

Answers (1)

approxiblue
approxiblue

Reputation: 7122

If you need to get the tags in JavaScript, you can define them in a <script> tag from the start. In your theme HTML:

<script>
    var tags = {};

    {block:Posts}
    {block:HasTags}
    tags[{JSPostID}] = [
        {block:Tags}
        {
            "tag": {JSTag},
            "tagURL": {JSTagURL},
        },
        {/block:Tags}
    ];
    {/block:HasTags}
    {/block:Posts}
</script>

You have a global JavaScript dictionary, from a post's ID to its list of tags (and tag URLs). The "JS" prefix is to output the string wrapped in quotes.

In each of your post elements, add an attribute for the post ID:

{block:Posts}
<article data-id="{PostID}" class="post"></article>
{/block:Posts}

You can have {block:Posts} multiple times in your template, although the theme documentation does not mention this.

Whenever you need a post's tags, get the post ID from its DOM element, then look up the ID in the tag dictionary. This way you don't have to worry about escaping/un-escaping special characters.

Upvotes: 2

Related Questions