Paginator doesn't override pagination settings - hugo

I'm using hugo 0.73.0, and the Paginator doesn't seem to override the global paginate value.
Question 1:
In my config.toml
paginate = 4
In my list template
{{ range (.Paginator 2).Pages -}}
{{ partial "listing.html" .}}
{{- end }}
Here I want to use 2 post per page but it still shows 4 as defined by the global setting in config.
Question 2:
When I try
{ range sort (.Paginate (.Site.Taxonomies.tags.Alphabetical)).Pages.ByTitle -}}
{{ partial "listing.html" .}}
{{- end }}
The list sorts my posts by name. But as soon as pagination kicks in, it messes up the sorting order. Eg. If I have 4 posts (A, B, C, D) and paginate is set to 3. then the pages are like this:
page 1: posts B, C, D
page 2: posts A
What I want is something like this
page 1: posts A, B, C
page 2: posts D
Any help will be appreciated. Thanks

The gohugo-theme-ananke shows 3 articles per pages, using layouts/posts/list.html with:
{{ $paginator := .Paginate (where .Data.Pages "Section" .Section)}}
Check if overriding the Paginate option would work in that theme example site, for testing.
Then you can try and integrate .Site.Taxonomies.tags.Alphabetical

Related

Hugo - using index with complex key to get data

Assuming the following urls.toml file in data folder:
[Group]
link = "http://example.com"
[Group.A]
link = "http://example.com"
I know that I can access the link value in Group.A in my shortcode like this:
{{ index .Site.Data.urls.Group.A "link" }}
But, I would like to access the link in a way similar to the following:
{{ index .Site.Data.urls "Group.A.link" }}
The reason for this is to enable me to pass the "Group.A.link" as a parameter to my "url" shortcode within the content markdown like this:
{{< url "Group.A.link" >}}
Otherwise, I won't be able to use nesting for logical organisation in the urls.toml data file.
Thanks in advance.
You can use nested calls of index COLLECTION "key" to narrow your way down.
Meaning,
(index (index (index .Site.Data.urls "Group") "A") "link")
would work given your urls.toml structure.
The trick is making it somewhat dynamic, so you don't need to worry too much about depth.
The snippet below might serve as a potential starting point for a shortcode. However, it doesn't have any safe-guards. I'd recommend to add a few checks to get meaningful errors/warnings if things go wrong.
{{ $path := .Get 0 }}
{{/* split the string to have indices to follow the path */}}
{{/* if $path is "A.B.C", $pathSlice wil be ["A" "B" "C"] */}}
{{ $pathSlice := split $path "." }}
{{ $currentValue := .Site.Data.urls }}
{{ range $pathSlice }}
{{/* recommended homework: check that $currentValue is a dict otherwise handle with defaults and/or warnings */}}
{{ $currentValue = index $currentValue . }}
{{ end }}
<p>et voila: {{ $currentValue }}</p>
After having looked at Hugo's code (Index function) I found a very simple solution.
If we want to pass a complex comma-separated key, all we need to do is split it when calling index. Example:
Using the url shortcode in markdown:
{{< url "Group.A.link" >}}
Code of the url shortcode:
{{ index .Site.Data.urls (split (.Get 0) ".")}}

How to add Search bar for django template?

I need a search bar in my template on top of my table. The search bar should search based on any table parameter, and filter the enteries accordingly.
I implemented the search bar using CSS classes and I get it as I wanted.
Now here's the views.py code.
def jobs(request):
jobs = Jobb.objects.all()
search_term = ''
if 'search' in request.GET:
search_term = request.GET['search']
jobs = jobs.filter(position__icontains=search_term)
context = {
'jobs': jobs, 'search_term': search_term, 'job': 'active'
}
return render(request, 'Job_openings/jobb.html',context)
This code does the job for me , but the problem is that it only searches the enteries based on my model return value.
def __str__(self):
return self.position
Thus, I'm only able to search all enteries having some specific 'position'.
My model has other fields like 'date posted', 'company name'..
I want the search bar to work for all such fields.
Lets say I enter a company name, and I get all the results from the list.
How can I achieve this? Thanks in advance.
you can use Q objects to perform "OR" queries.
from django.db.models import Q
jobs = jobs.filter(
Q(position__icontains=search_term) |
Q(your_other_field__icontains=search_term) |
Q(....)
)
then, in your template, you can access it with loop, and use dot "." to access the fields like:
{% for job_item in jobs %}
{{ job_item.position }}, {{ job_item.your_other_field }}
{% endfor %}

How to prevent duplicates when using ModelChoiceFilter in Django Filter and Wagtail

I am trying to use filters with a Wagtail Page model and a Orderable model. But I get duplicates in my filter now. How can I solve something like this?
My code:
class FieldPosition(Orderable):
page = ParentalKey('PlayerDetailPage', on_delete=models.CASCADE, related_name='field_position_relationship')
field_position = models.CharField(max_length=3, choices=FIELD_POSITION_CHOICES, null=True)
panels = [
FieldPanel('field_position')
]
def __str__(self):
return self.get_field_position_display()
class PlayerDetailPage(Page):
content_panels = Page.content_panels + [
InlinePanel('field_position_relationship', label="Field position", max_num=3),
]
class PlayerDetailPageFilter(FilterSet):
field_position_relationship = filters.ModelChoiceFilter(queryset=FieldPosition.objects.all())
class Meta:
model = PlayerDetailPage
fields = []
So what I am trying to do is create a filter which uses the entries from FIELD_POSITION_CHOICES to filter out any page that has this position declared in the inline panel in Wagtail.
As you can see in the picture down below, the filters are coming through and the page is being rendered. (These are 2 pages with a list of 3 field positions).
So Page 1 and Page 2 both have a "Left Winger" entry, so this is double in the dropdown. The filtering works perfectly fine.
What can I do to prevent this?
The solution should be something like this (Credits to Harris for this):
I basically have one FieldPosition object per page-field position, so it's listing all of the objects correctly. I suspect I should not use the model chooser there, but a list of the hard coded values in FIELD_POSITION_CHOICES and then a filter to execute a query that looks something like PlayerDetailPage.objects.filter(field_position_relationship__field_position=str_field_position_choice). But what is the Django Filter way of doing this?
Raf
In my limited simplistic view it looks like
class PlayerDetailPageFilter(FilterSet):
field_position_relationship = filters.ModelChoiceFilter(queryset=FieldPosition.objects.all())
is going to return all the objects from FieldPosition and if you have 2 entries for 'left wing' in here (one for page 1 and one for page 2) then it would make sense that this is duplicating in your list. So have you tried to filter this list queryset with a .distinct? Perhaps something like
class PlayerDetailPageFilter(FilterSet):
field_position_relationship = filters.ModelChoiceFilter(queryset=FieldPosition.objects.values('field_position').distinct())
I found the solution after some trial and error:
The filter:
class PlayerDetailPageFilter(FilterSet):
field_position_relationship__field_position = filters.ChoiceFilter(choices=FIELD_POSITION_CHOICES)
class Meta:
model = PlayerDetailPage
fields = []
And then the view just like this:
context['filter_page'] = PlayerDetailPageFilter(request.GET, queryset=PlayerDetailPage.objects.all()
By accessing the field_position through the related name of the ParentalKey field_position_relationship with __.
Then using the Django Filter ChoiceFilter I get all the hard-coded entries now from the choice list and compare them against the entries inside the PlayerDetailPage query set.
In the template I can get the list using the Django Filter method and then just looping through the query set:
<form action="" method="get">
{{ filter_page.form.as_p }}
<input type="submit" />
</form>
{% for obj in filter_page.qs %}
{{ obj }} >
{% endfor %}

Use variable inside Hugo content

I'm trying to use a variable within the content of a Hugo statically generated site. For example, the content looks like the following:
Go to your site's url ({{ .Site.BaseURL }})
Enter your credentials
.....(blah blah blah)
When this gets rendered, the {{ .... }} part doesn't get processed...it stays the same as I put above. I've tried it with a $ in front as well. Variables within templates seem to work just fine. Do I need to create a shortcode to use within content pages?
So it looks like a shortcode is the way to do this. For what it's worth, I changed the document to look like the following:
Go to your site's url ({{< siteurl >}})
In layouts/shortcodes, I created the file siteurl.html. It looks like the following:
{{ .Page.Site.BaseURL }}
I needed to add .Page in there to get access to the Site variables. See this Issue Report for more details.
In Hugo, When you want to use a variable in markdown (.md) file then you need to create a shortcode for that first.
You can follow these steps:-
create shortcode
layouts/shortcodes/siteurl.html
{{ .Page.Site.BaseURL }}
usage
content/post/myblogpost.md
---
# front-matter
---
1. Go to your site's url ({{< siteurl >}})
2. Enter your credentials
3. .....(blah blah blah)
result
post/myblogpost.html
1. Go to your site's url (https://codingnconcepts.com)
2. Enter your credentials
3. .....(blah blah blah)
Source: https://codingnconcepts.com/hugo/custom-shortcode-hugo/
I had the same problem, and this post helped me.
I wanted to display a site param in my site content, and discovered you cannot use regular templating inside content files.
In the end I created a shortcode to load the requested site param. Who knows this information might help someone.
/config.yml
params:
appName: My app
/content/about.html
<p>My app's name is {{< param "appName" >}}</p>
/layouts/shortcodes/param.html
{{/* Usage: {{< param "siteParamName" }} */}}
{{ index .Site.Params (.Get 0) }}
Result
<p>My app's name is My app</p>
This is an attempt to slightly improve #minitauros answer with a simplistic example to lookup a (site) parameter sub-key (aka walk the YAML tree, infer an element, etc.).
I would like Hugo to have a JSONPath or jq syntax and, obviously, this example is far from competing with either solutions.
config.yml
params:
mode: one
support:
mailing: info#example.net
layouts/shortcodes/param.html
{{ $v := .Site.Params }}
{{ range (split (.Get 0) ".") }}{{ $v = index $v (.) }}{{ end }}
{{ $v }}
content/_index.md
We are in mode {{< param "mode" >}}.
In case of turbulence, [reach the support](mailto:{{< param "support.mailing" >}}) for help.

How to query the number of elements stored in a db.ListProperty in google app engine

The entity class is defined like:
class Item(db.Model):
list = db.ListProperty(db.Key)
What's the attribute or function to return the number of elements stored in a ListProperty, so that I can use something like
{{ item.list.... }}
to display that in a html.
It's a list so you can use len() on it.
total = len(item.list)
or if you are using jinja on your html you can use the count filter
{{ item.list|count }}

Resources