I have a javascript function like this which is used with Select2.
function formatResult(item) {
var markup = '<div class="card">\
<div class="card-header">\
<div class="avatar">\
<img src="http://mysite/profile/' + item.Username + '_thumb.jpg"/>\
</div>\
<div class="name">' + item.FirstName + ' ' + item.LastName + '</div>\
<div class="title">' + item.Title + '</div>\
</div>\
</div>';
return markup;
}
And it works, although building the HTML is tedious when making it as a string.
What I would like to do is make this into a partial for easier maintainability and editing.
Ideally I want something like this.
function formatResult_User(item) {
var markup = '@Html.Raw(Html.Partial("_UserCardTemplate").ToString().Replace(Environment.NewLine, ""))';
return markup;
}
But how can I insert the item variables back in? Would I just put a placeholder value and use replace() on the markup variable such as markup = markup.replace('item.Title', item.Title)? Is there a better way?
<div class="title"></div>in the partial, and after the html has been added to the DOM, use$(element).find('.title').text(item.title);(and its not really necessary to create a separate partial - you can just create a (hidden) template and clone it)<div id="template" style="display:none;><div class="card">....</div></div>and thenvar clone = $('#template').html().clone(); // add to DOM, then clone.find('.title').text(item.title);inside your function