"""Plugin for including template snippets through the CMS"""fromcollectionsimportdefaultdictfromcontent_editor.adminimportContentEditorInlinefromdjango.dbimportmodelsfromdjango.db.modelsimportsignalsfromdjango.template.baseimportTemplatefromdjango.template.loaderimportrender_to_stringfromdjango.utils.translationimportgettext_lazyas_fromfeincms3.mixinsimportChoicesCharFieldfromfeincms3.rendererimportrender_in_context__all__=("Snippet","SnippetInline","render_snippet")
[docs]defrender_snippet(plugin,context=None,**kwargs):""" Renders the selected template using ``render_to_string`` """returnrender_to_string(plugin.template_name,{"plugin":plugin})
[docs]@staticmethoddeffill_template_name_choices(sender,**kwargs):""" Fills in the choices for ``template_name`` from the ``TEMPLATES`` class variable. This method is a receiver of Django's ``class_prepared`` signal. """ifissubclass(sender,Snippet)andnotsender._meta.abstract:sender._meta.get_field("template_name").choices=[choice[:2]forchoiceinsender.TEMPLATES]
[docs]@classmethoddefregister_with(cls,renderer,**kwargs):""" This helper registers the snippet plugin with a ``TemplatePluginRenderer`` while adding support for template-specific context functions. The templates specified using the ``TEMPLATES`` class variable may contain a callable which receives the plugin instance and the template context and returns a context dictionary. """fromfeincms3.rendererimportdefault_contexttemplates=defaultdict(lambda:Template(""),((row[0],row[0])forrowincls.TEMPLATES),)context_fns=defaultdict(lambda:default_context,[(row[0],row[2])forrowincls.TEMPLATESiflen(row)>2],)def_render_snippet(plugin,context):returnrender_in_context(context,templates[plugin.template_name],context_fns[plugin.template_name](plugin,context),)renderer.register(cls,_render_snippet,**kwargs)
[docs]classSnippetInline(ContentEditorInline):""" Snippet inline does nothing special, it simply exists for consistency with the other feincms3 plugins """button='<span class="material-icons">smart_toy</span>'