How to get all posts for each category in a template file?

83 views
Skip to first unread message

Miki

unread,
Jan 3, 2018, 6:08:11 AM1/3/18
to nikola-discuss
Hello,
if i'm correct, currently Nikola displays posts for each category only as a separate page with links.

To make my blog easier to navigate, my goal is to create a sorted tree that would show all posts (titles, links) for each category on a single page. Ideally such navigation tree would be displayed in a side panel on each page. So, something like other blog engines already have.

I guess I should modify some template file to do this. I tried tags.tmpl in bootstrap3-jinja, but i don't know how to access all posts from the template file and get their attributes (title, link, categories, tags).
Only thing I can do is this:

   {% for category in cat_items %}
       
<li>{{ category[0] }} <!-- Get category name -->
           
<ul>
               
<!-- How to get all posts for give category here??? -->
           
</ul>
        </
li>
   
{% endfor %}

So my question is, how can I get posts (and their titles, links, etc) for each given category in a jinja template file?

Thank you in advance.

Chris Warrick

unread,
Jan 3, 2018, 7:02:58 AM1/3/18
to Nikola—Discuss
You can't do it directly in templates. We don't have all posts available in all templates, since that would cause rebuilds of *all* pages every time a post changes.

However, there is a solution for this. For the list of posts, create a page using the post list reST directive. To use it on every page, create a per-page empty template, and then include it either via a server-side include mechanism, or via JS. You can look at the sources of our plugins and themes sites for an example (search for `sidemenu` in the site subdirectory of their GitHub repos).

--
Chris Warrick <https://chriswarrick.com/>

--
You received this message because you are subscribed to the Google Groups "nikola-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nikola-discuss+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Miki

unread,
Jan 3, 2018, 10:31:33 AM1/3/18
to nikola-discuss
Thank you lots for the prompt answer Chris.

However, it's more complicated than I thought. I found and tried to install this plugin sidebar, but my site refuses to build with it (perhaps because my site has only single language). And actually I'm not sure if the sidebar does what I need (show posts tree sorted by categories).

Then I looked how to create a reST page which would display all categories/tags and their posts. I see there is the post-list command which can print all posts for given category/tag. But what I can't find is how to cycle trough all categories to run the post-list command for each category. Is there any way how to get lists of categories/tags in a reST page?

Alternatively, is there any template which exposes posts and their categories, if I wanted to have only one single page for my site navigation (instead of including it in all pages)? I see there is this archiveindex template which prints all posts, but is it possible to get category of each post, so i could reorganize the posts data in jinja-python code?

Chris Warrick

unread,
Jan 3, 2018, 10:40:42 AM1/3/18
to Nikola—Discuss
On 3 January 2018 at 16:31, Miki <mesh...@gmail.com> wrote:
> Thank you lots for the prompt answer Chris.
>
> However, it's more complicated than I thought. I found and tried to install
> this plugin sidebar, but my site refuses to build with it (perhaps because
> my site has only single language). And actually I'm not sure if the sidebar
> does what I need (show posts tree sorted by categories).

I think you could write a template that would do it. The plugin
requires a custom messages file by default, although you can just
replace the template tags with raw text.

> Then I looked how to create a reST page which would display all
> categories/tags and their posts. I see there is the post-list command which
> can print all posts for given category/tag. But what I can't find is how to
> cycle trough all categories to run the post-list command for each category.
> Is there any way how to get lists of categories/tags in a reST page?

> Alternatively, is there any template which exposes posts and their
> categories, if I wanted to have only one single page for my site navigation
> (instead of including it in all pages)? I see there is this archiveindex
> template which prints all posts, but is it possible to get category of each
> post, so i could reorganize the posts data in jinja-python code?

For the other two ideas,I’m afraid there isn’t anything built-in.

I can think of three solutions:
1. try to get `sidebar` to work (iterate over category list or something?)
2. use post-list, create some functions (conf.py → GLOBAL_CONTEXT)
that figure out list of categories in them and then produce (category,
posts) pairs or whatever
3. write a custom plugin

(All three would still work best with server-side includes/JS)

--
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16

Miki

unread,
Jan 5, 2018, 7:14:46 AM1/5/18
to nikola-discuss
Hi Chris, thank you very much for your prompt answers, it's very helpful for me :)

I managed to make the sidebar working (it took me a while to realize that <!-- --> has no effect in jinja templates to remove the problematic language parts). It generates the sidebar-en.inc file which I included by jQuery into base.tmpl, so it appears on every page.

Particularly, I added this function into customs.js
$(function(){
    $
("#include-sidebar").load("/sidebar-en.inc");
});

and then just added this into base.tmpl
<div id="include-sidebar"></div>

Now, i just need to play with CSS to make the sidebar fit into my site. I think this sidebar is really cool, and when sub-categories enabled, it improves site navigation lots and lots... and i bet it can be styled to look like the navigation widgets in wordpress.
 
May I have one more question? When editing templates, like index.tmpl, where i can find all attributes of the post object? I see the page template-variables but it only refers to the Post type, but is there any doc to specify all its attributes and methods? Thank you again.







Chris Warrick

unread,
Jan 5, 2018, 9:02:57 AM1/5/18
to Nikola—Discuss
On 5 January 2018 at 13:14, Miki <mesh...@gmail.com> wrote:
> May I have one more question? When editing templates, like index.tmpl, where
> i can find all attributes of the post object? I see the page
> template-variables but it only refers to the Post type, but is there any doc
> to specify all its attributes and methods? Thank you again.

You can look at the source code:
master (v8 dev) https://github.com/getnikola/nikola/blob/master/nikola/post.py
v7-maintenance https://github.com/getnikola/nikola/blob/v7-maintenance/nikola/post.py

MAVignau

unread,
Jan 6, 2018, 3:09:15 PM1/6/18
to nikola-discuss
post = {Post} <Post: 'posts/0055.rst' 4f1fe96f3a5299d0d8e3976bb1da3590>
 _base_path = {str} 'cache/posts/0055.html'
 _dependency_file_fragment = {defaultdict} defaultdict(<class 'list'>, {'es': [(True, <function PageCompiler.register_extra_dependencies.<locals>.create_lambda.<locals>.<lambda> at 0x7f7a6bd1d400>)], None: []})
 _dependency_file_page = {defaultdict} defaultdict(<class 'list'>, {'es': [], None: []})
 _dependency_uptodate_fragment = {defaultdict} defaultdict(<class 'list'>, {'es': [], None: []})
 _dependency_uptodate_page = {defaultdict} defaultdict(<class 'list'>, {'es': [], None: []})
 _depfile = {defaultdict} defaultdict(<class 'list'>, {})
 _next_post = {NoneType} None
 _paragraph_count = {int} 10
 _prev_post = {Post}
 _reading_time = {int} 3
 _remaining_paragraph_count = {int} 0
 _remaining_reading_time = {int} 1
 _tags = {dict} {'es': []}
 _template_name = {str} 'post.tmpl'
 alltags = {list} <class 'list'>
 base_path = {str}
 base_url = {str}
 compiler = {CompileRest} <yapsy_loaded_plugin_rest_0.CompileRest object at 0x7f7a6bda6e10>
 config = {dict} {'USE_BUNDLES': False, 'TIMEZONE':'', 'CATEGORY_OUTPUT_FLAT_HIERARCHY': False, 'TAGLIST_MINIMUM_POSTS': 1, 'LICENSE': <TranslatableSetting: 'LICENSE'>, 'THEME_COLOR': '#5670d4', 'GZIP_COMMAND': None, 'TAG_TRANSLATIONS': [], '
 current_time = {datetime} 2018-01-06 17:05:50.854680-03:00
 data = {Functionary} defaultdict(<function Post.__init__.<locals>.<lambda> at 0x7f7a6bd1d268>, {})
 date = {datetime} 2005-06-28 06:04:58-03:00
 default_lang = {str} 'es'
 demote_headers = {int} 1
 folder = {str} 'posts'
 folder_base = {TranslatableSetting} posts
 folder_relative = {str} '.'
 folders = {dict} {'es': 'posts'}
 hyphenate = {bool} False
 index_file = {str} 'index.html'
 is_draft = {bool} False
 is_mathjax = {bool} False
 is_post = {bool} True
 is_private = {bool} False
 is_two_file = {bool} False
 messages = {Functionary} defaultdict(<class 'dict'>, {'es': {'%d min remaining to read': 'quedan %d minutos de lectura', 'Authors': 'Autores', 'Older posts': 'Publicaciones anteriores', 'old posts, page %d': 'publicaciones antiguas, página %d', 'Skip to main content': 'Ir al conte
 meta = {Functionary} defaultdict(<function Post.__init__.<locals>.<lambda> at 0x7f7a6bd7f840>, {'es': defaultdict(<function get_meta.<locals>.<lambda> at 0x7f7a6bd7f7b8>, {'date': '2005-06-28 06:04:58', 'url_type': '', 'template': '', 'password': '', 'filters': '', 'tags': 'co
 metadata_path = {str} 'posts/0055.meta'
 newstylemeta = {bool} True
 next_post = {NoneType} None
 paragraph_count = {int} 10
 post_name = {str} 'posts/0055'
 pretty_urls = {bool} True
 prev_post = {Post} <Post: 'posts/0054.rst' 140e03e312f09bea0e0415514f76ef60>
 previewimage = {NoneType} None
 publish_later = {bool} False
 reading_time = {int} 3
 remaining_paragraph_count = {int} 0
 remaining_reading_time = {int} 1
 skip_untranslated = {bool} False
 source_path = {str} 'posts/0055.rst'
 strip_indexes = {bool} True
 tags = {list} <class 'list'>: []
 template_name = {str} 'post.tmpl'
 translated_to = {set} {'es'}
 translations = {dict} {'es': ''}
 updated = {datetime}
 url_type = {NoneType} None
 use_in_feeds = {bool} True

童虎

unread,
Apr 14, 2018, 10:18:46 PM4/14/18
to nikola-discuss
Hello, I flow your guid.
First create a page name test.org which specify the template test.tmpl:

#+begin_comment
.. title: 2017 learn list
.. slug: 2017_learn_list
.. date: 2017-09-19 22:10:06 utc+08:00
.. tags:
.. category:
.. link:
.. description:
.. type: text
.. template: test.tmpl
#+end_comment


fdioafdjaiofdsa

Then in my test.tmpl, I let it extends index.tmpl

## -*- coding: utf-8 -*-
<%inherit file="index.tmpl"/>

<%block name="content">
<p>HAHAHAHAH</p>
<p>BBB</
p>
<p>${posts}</p>
</%block>



But still the posts variable is undefined. Can you tell me which step I did wrong?


在 2018年1月3日星期三 UTC+8下午8:02:58,Chris Warrick写道:
To unsubscribe from this group and stop receiving emails from it, send an email to nikola-discus...@googlegroups.com.

Chris Warrick

unread,
Apr 15, 2018, 5:39:19 AM4/15/18
to Nikola—Discuss
On 15 April 2018 at 04:18, 童虎 <huhu...@gmail.com> wrote:
> Hello, I flow your guid.
> First create a page name test.org which specify the template test.tmpl:
>
> #+begin_comment
> .. title: 2017 learn list
> .. slug: 2017_learn_list
> .. date: 2017-09-19 22:10:06 utc+08:00
> .. tags:
> .. category:
> .. link:
> .. description:
> .. type: text
> .. template: test.tmpl
> #+end_comment
>
>
> fdioafdjaiofdsa

You need to use the post-list directive:
https://getnikola.com/handbook.html#post-list

It is recommended to use a reST page for this, not orgmode.

> Then in my test.tmpl, I let it extends index.tmpl
>
> ## -*- coding: utf-8 -*-
> <%inherit file="index.tmpl"/>
>
> <%block name="content">
> <p>HAHAHAHAH</p>
> <p>BBB</p>
> <p>${posts}</p>
> </%block>

You won’t be able to access the `posts` variable in templates even if
you use post-list. You will need to provide a post-list template (or
use the default one) to format the post list. (You would be able to
display post content with it.)

Here’s the setup from themes.getnikola.com (menu on the right that
appears on theme pages):

https://raw.githubusercontent.com/getnikola/nikola-themes/master/site/pages/sidemenu.rst
https://github.com/getnikola/nikola-themes/blob/master/site/templates/sidemenu.tmpl
https://github.com/getnikola/nikola-themes/blob/master/site/templates/sidemenu_list.tmpl

--
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16

童虎

unread,
Apr 15, 2018, 10:13:06 AM4/15/18
to nikola-discuss
Got it! Thank you!

在 2018年4月15日星期日 UTC+8下午5:39:19,Chris Warrick写道:
Reply all
Reply to author
Forward
0 new messages