combo/combo/apps/assets/templatetags/assets.py

67 lines
2.0 KiB
Python

# combo - content management system
# Copyright (C) 2017-2018 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django import template
from django.db.models.fields.files import ImageFieldFile
from django.utils import six
from sorl.thumbnail.shortcuts import get_thumbnail
from ..models import Asset
register = template.Library()
@register.simple_tag
def asset_url(*args, **kwargs):
asset = None
for asset_object in args:
if isinstance(asset_object, ImageFieldFile):
try:
asset_object.url
except ValueError: # no associated file
continue
asset = asset_object
break
if isinstance(asset_object, six.string_types):
try:
asset = Asset.objects.get(key=asset_object).asset
break
except Asset.DoesNotExist:
continue
if isinstance(asset_object, Asset):
asset = asset_object.asset
break
if not asset:
return ''
geometry_string = kwargs.pop('size', None)
if not geometry_string or asset.file.name.endswith('svg'):
return asset.url
return get_thumbnail(asset, geometry_string, **kwargs).url
@register.assignment_tag
def get_asset(key):
try:
return Asset.objects.get(key=key)
except Asset.DoesNotExist:
return None