applegrew / django-select2

This is a Django integration for Select2
MIT License
712 stars 314 forks source link

render a dropdown as a html #562

Closed kabrachups closed 5 years ago

kabrachups commented 5 years ago

I want to render a dropdown in Django-Select2 as a html. Something like this: https://select2.org/dropdown#templating

But I couldn't find it in the docs. Is it possible?

codingjoe commented 5 years ago

Hi @kabrachups,

Thanks for reaching out. This is indeed possible, this package is written, so that it can be extended easily.

JS Code:

(function ($) {
    function formatOption(data) {
       return `<div>{data.title}</div>`
    }
    function initCallback($element) {
        const settings = {
            containerCssClass: 'my-widget-container',
            escapeMarkup: function(markup){ return markup },
            templateResult: formatOption,
            templateSelection: formatOption,
        };
        $element.djangoSelect2(settings);
    }
  initCallback($('.my-widget'));
})(window.jQuery)

Python Code

class MyWidget(ModelSelect2Widget):
    def build_attrs(self, *args, **kwargs):
        attrs = super().build_attrs(*args, **kwargs)
        attrs['class'] = attrs['class'].replace('django-select2', 'my-widget', 1)
        return attrs

    @property
    def media(self):
        return forms.Media(
            js=ModelSelect2Widget.media.js + ('myapp/js/my_widget.js',),
            css=ModelSelect2Widget.media.css,
        )

I haven't tested the code, but maybe we should add a working example to the documentation. Maybe you want to contribute this documentation yourself, once you made it working yourself?

Let me know if you have any further questions.

Best -Joe