Skip to content

Instantly share code, notes, and snippets.

@runfalk
Created May 30, 2017 19:37
Show Gist options
  • Save runfalk/0cf737c9340df2716351c88689cd0d9a to your computer and use it in GitHub Desktop.
Save runfalk/0cf737c9340df2716351c88689cd0d9a to your computer and use it in GitHub Desktop.
import itertools
import os
import re
from lektor.db import F
from lektor.types import SelectType
from lektor.pluginsystem import Plugin
class AttachmentType(SelectType):
def __init__(self, env, options):
super(AttachmentType, self).__init__(env, options)
self.attachment_types = []
if "attachment_types" in options:
self.attachment_types = re.split(
"\s*\,\s*", options.get("attachment_types"))
def to_json(self, pad, record=None, alt='_primary'):
# Filter attachment list if there are any attachment_types specified
attachments = record.attachments
for at in self.attachment_types:
attachments = attachments.filter(F._attachment_type == at)
# Re-use SelectType's output but force the choices option to an
# attachment file
output = super(AttachmentType, self).to_json(pad, record, alt)
output["choices"] = [
[os.path.basename(att.path)] * 2
for att in attachments
]
return output
class AttachmentTypePlugin(Plugin):
"""
Attachment Field Type
This plugin adds a new field type which adds a select-input that displays
all attachments associated with the current Record. To use it, simply set
``type = attachment`` for a field in your model file. to force attachments
of certain types only, set ``attachment_types = image, document`` for
instance.
To add a new type add ``.ext = type_name`` to the ``[attachment_types]``
section in your ``.lektorproject`` file.
"""
name = "Attachment type"
description = re.sub(r"\s+", " ", __doc__.split("\n\n", 1)[1])
def on_setup_env(self, **extra):
self.env.add_type(AttachmentType)
from setuptools import setup
setup(
name="lektor-attachment-type",
version="0.1",
py_modules=["lektor_attachment_type"],
entry_points={
"lektor.plugins": [
"attachment-type = lektor_attachment_type:AttachmentTypePlugin",
]
},
install_requires=[]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment