doukongpao0903 2019-03-04 05:18
浏览 52

动态抓取最新发布的OctoberCMS Blog插件

I asked this question in the October forums but 12 hours later the post still says "unapproved" and I don't believe it's visible. Here's a copy-paste:

What I want to do is grab the latest blog post and display it on the homepage of the website. I can do it currently with my own post partial and the posts variable injected by the blogPosts component like so:

[blogPosts]
pageNumber = "{{ :page }}"
postsPerPage = 10
noPostsMessage = "No posts found"
sortOrder = "published_at desc"
categoryPage = "blog/category"
postPage = "blog/post"
==
{% partial 'site/blogpost' post=posts|last %}

However, I'd like to do this with the default blogpost component that comes with the plugin, but the only way to pass the post to the component seems to be by using the slug in the url, which doesn't really work for the homepage. How can I achieve this?

  • 写回答

2条回答 默认 最新

  • duan1396 2019-03-04 06:58
    关注

    So, as with most things when it comes to development... RTFM.

    All the info I needed was in the Components section of the October CMS docs, and of course I was only looking in the plugin docs. What I ended up doing was overriding the default component partial with my own and then passing the slug to the component. My original reason for wanting to use the default partial was that my custom partial wasn't rendering images, but the default would. I just needed to steal the line <p>{{ post.content_html|raw }}</p> to get that to work.

    [blogPost]
    ==
    ...
    {% component 'blogPost' slug=posts|last.slug %}
    

    Additional info: With the above solution your template pulls all blog posts in the database, which means if you have a lot of posts this could (and most likely will) affect performance. Turns out October templates have a PHP section. The proper thing to do is to remove the blogPosts component and grab the latest post Model like so:

    [blogPost]
    ==
    <?
      use RainLab\Blog\Models\Post;
    
      function onStart()
      {
        $this['latestPost'] = Post::latest()->first();
      }
    ?>
    ==
    {% component 'blogPost' slug=latestPost.slug %} 
    

    Note: The blogPost component injects a post variable which will override a post variable defined in the PHP section. This is way the variable is labeled latestPost.

    评论

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入