from photologue.models import Photo, PhotoSize from docutils import nodes from docutils.parsers.rst import directives from docutils.parsers.rst.directives.images import image OPTIONS = { 'alt': directives.unchanged, 'class': directives.class_option } def imageblock_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """ Directive for inserting images using photolouge in django. Syntax: .. imageblock:: photo_title_slug photo_size_name left|right|center :class: optionalclassoption optional description for image, can be multiple lines """ try: slug, attr, pos = arguments[0].split(' ') except ValueError: error = state_machine.reporter.error( 'Error in "%s" directive: Too many arguments. ' 'Valid arguments are "title_slug image_size position". ' % (name,) , nodes.literal_block(block_text, block_text), line=lineno) return [error] if pos not in ('left', 'right', 'center'): error = state_machine.reporter.error( 'Error in "%s" directive: "%s" is not a valid position for ' 'images. Valid positions are: "left right center". ' % (name, pos) , nodes.literal_block(block_text, block_text), line=lineno) return [error] img = Photo.objects.get(title_slug=slug) try: imgurl = getattr(img, 'get_%s_url' % attr)() except AttributeError: error = state_machine.reporter.error( 'Error in "%s" directive: "%s" is not a valid size for ' 'images. Valid sizes are: "%s" ' % (name, attr, ", ".join([s.name for s in PhotoSize.objects.all()]) ) , nodes.literal_block(block_text, block_text), line=lineno) return [error] imgsize = getattr(img, 'get_%s_size' % attr)() options['width'] = str(imgsize[0]) options['height'] = str(imgsize[1]) if not 'alt' in options: options['alt'] = img.title text = '\n'.join(content) node = nodes.container(text) classes = ['imageblock', '%simage' % attr, '%spos' % pos] if 'class' in options: classes.append(''.join(options['class'])) del options['class'] node['classes'].extend(classes) imagenode = image(name, [imgurl], options, content, lineno, content_offset, block_text, state, state_machine) node.insert(0, imagenode) state.nested_parse(content, content_offset, node) return [node] imageblock_directive.arguments = (1, 0, 1) imageblock_directive.content = 1 imageblock_directive.options = OPTIONS directives.register_directive('imageblock', imageblock_directive)