简体   繁体   中英

Wagtail routablepageurl for global search functionlity

I'm trying to add search functionlity in the header of the website so it's global but I'm having an issue with the context part of Routable Pages because I don't know how to set it so that it always links to the HomePage model no matter the URL.

For example, this works on the homepage seeing as self is the homepage.

{% routablepageurl self 'post_search' %}

However, if I go to the blog page (localhost:8000/blog/) it doesn't work because "self" should be the homepage. So with my limited knowledge I understand what the issue is but have no idea how to go about solving it.

I did try:

{% routablepageurl homepage 'post_search' %}

but I get the error 'str' object has no attribute 'relative_url'

I know I could go through every Model and pass in the HomePage into the context but surely there is a better way to do this?

The reason why I have added this to the HomePage is because I want the URL to be domain.com/search/

class HomePage(RoutablePageMixin, Page):
    template = 'lr/home/home_page.html'
    
    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        context['no_webpage_title'] = True
        return context

    class Meta:
        verbose_name = 'R HomePage'

    @route(r'^search/$', name='post_search')
    def post_search(self, request, *args, **kwargs):
        context = self.get_context(request)

        search_query = request.GET.get('q', None)
        self.posts = BlogDetailPage.objects.live().public().order_by('-last_published_at')
        if search_query:
            self.posts = self.posts.search(search_query)
            print(self.posts)
        return render(request, 'global/search_results_page.html', context)

Simple answer: If you've decided that your search URL will be /search/ and there will be no reason ever to change it, then don't bother trying to get {% routablepageurl %} to output an answer you already know - just write <form action="/search/"> .

More complex answer: Implement your search form as an inclusion tag . This will allow you to write a template for the search form, along with a Python function to set up the variables you want to pass to that template. Within that Python function, you can retrieve the HomePage instance (probably with HomePage.objects.first() ), call reverse_subpage on it to retrieve the search URL, and pass that to the template as part of the context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM