我目前正在提高Symfony 4的技能.
我被困在一个小问题上.
我想在上面添加一个分页,所以我检查了KpnPaginator,它的工作非常好.
这是代码,
控制器:
/**
* @Route("/blog", name="blog")
* @param ArticleRepository $repo
* @param Request $request
* @param PaginatorInterface $paginator
* @return \Symfony\Component\HttpFoundation\Response
*/
public function index(ArticleRepository $repo, Request $request, PaginatorInterface $paginator)
{
/*
* $repo = $this->getDoctrine()->getRepository(Article::class);
*/
$articlesQuery = $repo->findAll();
// Paginate the results of the query
$articles = $paginator->paginate(
// Doctrine Query, not results
$articlesQuery,
// Define the page parameter
$request->query->getInt('page', 1),
// Items per page
5
);
return $this->render('blog/index.html.twig', [
'controller_name' => 'BlogController',
'articles' => $articles
]);
}
风景 :
{% extends 'base.html.twig' %}
{% block title %}Hello {{ controller_name }}!{% endblock %}
{% block body %}
<section class="articles" id="">
{% for article in articles %}
<article>
<h2>{{ article.title }}</h2>
<div class="Metadata">Written on {{ article.createdAt | date('d/m/Y') }}
at {{ article.createdAt | date('H:i') }}, in Politic Category
</div>
<div class="content"><img src="{{ article.image }}" alt="">{{ article.content | raw }}
<a href="{{ path('blog_show', {'id': article.id}) }}" class="btn btn-primary">Read moree</a>
</div>
</article>
{% endfor %}
</section>
<br>
{{ knp_pagination_render(articles) }}
{% endblock %}
我的问题是
如何通过ajax请求使其工作?
解决方法:
您需要在JavaScript中设置一个onclick处理程序,以对ArticleController进行AJAX调用.
您可以使用如下形式:
$(document).ready(function() {
var $div = $('.articles');
$.ajax({
method: 'GET',
url: '/api/articles' + window.location.search,
headers: {
'Accept':'application/json',
'Content-Type':'application/json'
},
dataType: 'json',
success: function(data){
$.each(data.items, function(key, article) {
var html = articleTemplate(article);
$div.append($.parseHTML(html));
});
}
});
});
const articleTemplate = (article) =>
`<article>
<h2>${ article.title }</h2>
<div class="Metadata">Written on ${ article.createdAt }}
at ${ article.createdAt }, in Politic Category
</div>
<div class="content"><img src="${ article.image }" alt="">${ article.content }
<a href="{{ Routing.generate('blog_show', {'id': article.id}) }}" class="btn btn-primary">Read more</a>
</div>
</article>`;
这是使用ES6 JavaScript模板字符串来更新页面上的HTML,因此您可以从Twig模板中删除此部分.如果要在JavaScript中使用路由,则还需要安装FOSJSRoutingBundle-https://symfony.com/doc/master/bundles/FOSJsRoutingBundle/index.html
您将需要使ArticleController返回JSON响应,JavaScript处理程序将使用该JSON响应来更新页面.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。