from __future__ import absolute_import

from django.template import Library
from django.template.defaulttags import URLNode, url

from django.conf import settings

register = Library()


class AssetURLNode(URLNode):
    def render(self, context):
        path = super(AssetURLNode, self).render(context)
        parts = path.split('/')
        last = parts[-1]

        try:
            parts[-1] = settings.ASSET_MANIFEST[last]
        except IndexError:
            return path

        return '/'.join(parts)


@register.tag
def asset_url(parser, token, node_cls=AssetURLNode):
    """
        Just like the "url" templatetag, except replaces the filename part of
        the url path with the versioned filename pulled from the asset manifest
        generated by webpack.

        Example:
          {% asset_url 'sentry-media' 'sentry' 'dist/sentry.css' %}
          =>  "/_static/sentry/dist/sentry.74d127b78dc7daf2c51f.css"
    """

    node_instance = url(parser, token)

    return node_cls(view_name=node_instance.view_name,
        args=node_instance.args,
        kwargs=node_instance.kwargs,
        asvar=node_instance.asvar)

from __future__ import absolute_import

from django.template import Library
from django.template.defaulttags import URLNode, url

from django.conf import settings

register = Library()


class AssetURLNode(URLNode):
    def render(self, context):
        path = super(AssetURLNode, self).render(context)
        parts = path.rsplit('/', 1)
        last = parts[-1]

        try:
            parts[-1] = settings.ASSET_MANIFEST[last]
        except IndexError:
            return path

        return '/'.join(parts)


@register.tag
def asset_url(parser, token, node_cls=AssetURLNode):
    """
        Just like the "url" templatetag, except replaces the filename part of
        the url path with the versioned filename pulled from the asset manifest
        generated by webpack.

        Example:
          {% asset_url 'sentry-media' 'sentry' 'dist/sentry.css' %}
          =>  "/_static/sentry/dist/sentry.74d127b78dc7daf2c51f.css"
    """

    node_instance = url(parser, token)

    return node_cls(view_name=node_instance.view_name,
        args=node_instance.args,
        kwargs=node_instance.kwargs,
        asvar=node_instance.asvar)

use rsplit