JSrender未在模板中显示函数返回

jsrender not displaying function return in template

本文关键字:显示 函数 返回 JSrender      更新时间:2023-09-26

我有两个返回简单字符串的函数。两者都已注册。

$.views.helpers({
    parseDate: function (jsonDate) {
        if (jsonDate != null) {
            var date = new Date(parseInt(jsonDate.substr(6)));
            var newDate = $.fullCalendar.formatDate(date, "MM/dd/yyyy");
            return newDate;
        }
    },
    renderPrimaryResource: function (PrimaryResource, LessonID) {
        debugger;
        $.ajax({
            url: "cl/lb",
            dataType: "json",
            data: { id: PrimaryResource.ResourceID },
            type: 'GET',
            async: false,
            success: function (data) {
                var thumbnailImage = data[1];
                return thumbnailImage;
            }
        });
    }
});

我的 jsrender 模板调用这两个函数。解析日期函数被调用并按预期返回。第二个函数被调用并返回一些东西,但 jsrender 没有拾取它?不知道会发生什么,但它被完全忽略了。

<script id="LessonDetailTemplate" type="text/x-jsrender">
{{for lessons}}
    <div class="row lesson-block">
        <div class="span4">
            <h4>{{:LessonName}}</h4>
            <span><strong>Due on <span>{{:~parseDate(DueDate)}}</span>
            <br/>
            <p>{{:LessonDescription}}</p>
        </div>
        <div class="span4">
            <span">{{:~renderPrimaryResource(PrimaryResource, LessonID)}}</span>
        </div>
    </div>
{{/for}}

有人知道为什么这不渲染吗?我唯一能想到的是 ajax 调用,但在调试时模板不会继续,直到函数返回一些内容。所以我对正在发生的事情感到茫然。

回答以防有人偶然发现这一点。问题实际上出在 ajax 调用上。不确定它到底是什么,但您无法从 ajax 调用的成功部分返回字符串。修改了函数如下,工作正常。

renderPrimaryResource: function (PrimaryResource, LessonID) {
    debugger;
    $.ajax({
        url: "cl/lb",
        dataType: "json",
        data: { id: PrimaryResource.ResourceID },
        type: 'GET',
        async: false,
        success: function (data) {
            var thumbnailImage = data[1];
        }
    });
    if(thumbnailImage != null){
        return thumbnailImage;
    }
}