How to render html in select2 options

后端 未结 5 946
傲寒
傲寒 2020-12-25 10:46

In this example of data loaded from a remote source I can see images and other html elements rendered as options. I\'d like to accomplish the same thing using data in a loc

5条回答
  •  生来不讨喜
    2020-12-25 11:21

    Ok, played with this for a while and found a working solution so I'll answer my own question here.

    The key here for me is to build a data array with content for both templateSelection and templateResult. The latter renders fine in the dropdown but any multiline content will not be contained in the select2 element so needs to be displayed inline (or at least on a single line). Defining escapeMarkup as an option allows overriding of the core function which would normally strip out html content.

    It's also important to define the title attribute since otherwise you'll end up with html tags in the tooltip.

    var data = [{
      id: 0,
      text: '
    enhancement
    ', html: '
    enhancement
    Select2 supports custom themes using the theme option so you can style Select2 to match the rest of your application.
    ', title: 'enchancement' }, { id: 1, text: '
    bug
    ', html: '
    bug
    This is some small text on a new line
    ', title: 'bug' }]; $("select").select2({ data: data, escapeMarkup: function(markup) { return markup; }, templateResult: function(data) { return data.html; }, templateSelection: function(data) { return data.text; } })
    
    
    
    
    

    Alternately, with a couple small CSS tweaks you can allow the full html option content to display inside of the select container without the need for the template callbacks:

    var data = [{
      id: 0,
      text: '
    enhancement
    Select2 supports custom themes using the theme option so you can style Select2 to match the rest of your application.
    ', title: 'enchancement' }, { id: 1, text: '
    bug
    This is some small text on a new line
    ', title: 'bug' }]; $("select").select2({ data: data, escapeMarkup: function(markup) { return markup; } })
    .select2-container .select2-selection--single {
      height: auto!important;
      padding: 5px 0;
    }
    .select2-container--default .select2-selection--single .select2-selection__rendered {
      line-height: normal!important;
    }
    .select2-container .select2-selection--single .select2-selection__rendered {
      white-space: normal!important;
    }
    
    
    
    
    

提交回复
热议问题