【发布时间】:2018-08-31 02:09:27
【问题描述】:
如果我将数据(来自 Laravel 5.3 的 api 调用)加载到其中,我得到了一个发帖模板 (Hogen.js)。
我设法正确加载、编译和渲染模板和数据。
问题:
我有 jquery/vanilla js 脚本,需要使用模板和数据,但不知何故,这个 JS 被渲染的模板完全忽略并且它不起作用(onClick、其他 ajax 调用等)。
我的加载/渲染 JS:
var $page = 1;
var source = $("#postTemplate").html();
var template = Hogan.compile(source);
$.ajax({
url: '/api/postings',
data: { page: $page} ,
type: 'POST',
success: function(data) {
var output = template.render(data);
$('.posts-container').prepend(output);
}
});
我的模板:
<script id="postTemplate" type="text/x-hogan-template">
@{{#posts.data}}
<div class="post">
<div class="image">
<img src="@{{ imageURL }}" alt="post image" />
</div>
<div class="info">
<div class="like-count" data-like-id="@{{ id }}">
more html
</div>
</div>
@include('partials.comments')
</div>
@{{/posts.data}}
</script>
我在需要执行的“评论”代码中包含来自 laravel 的部分代码(淡入淡出、ajaxacalls、提交等)
是否有可能,我无法使用新呈现的模板或 DOM 执行我的 JS,因为它在 document.ready 中不可用?
我需要切换我的模板引擎吗?还有其他方法可以使这项工作吗?
JSON:
{
"success": true,
"posts": {
"total": 46,
"per_page": 20,
"current_page": 3,
"last_page": 3,
"next_page_url": null,
"prev_page_url": "http://localhost/api/postings?page=2",
"from": 41,
"to": 46,
"data": {
"40": {
"id": 6,
"name": " ",
"imageURL": "",
"city": "Spanien",
"country": "",
"created_at": "2018-03-11 09:40:25",
"profilePictureURL": null,
"social_src": 0,
"mediumImageURL": null
}
}
}
}
我把它删掉了一点!
【问题讨论】:
-
你能发布一个传递给成功函数的 JSON 样本吗?这样我可以给出更准确的答案。
-
我把它删掉了一点!
-
但问题是,最初的第一个模板完全没问题。我需要的JS没有执行。
标签: javascript templates laravel-5 mustache hogan.js