Playing Next Lesson In
seconds

Defining Our AdonisJS Filter Form Handler

@tomgobich
Published by
@tomgobich
In This Lesson

We'll expand on the filter query we built in the last lesson by reusing the query within a service for our filter form handler.

Join the Discussion 2 comments

Create a free account to join in on the discussion
  1. @virimchi-m

    Hi, if a request is NOT a HTMX I want the response to be embedded in the @layout. But if it is a HTMX request, I want the response to be from the edge template alone without the enclosing content such as Header, footer. How do you handle this? Are you having a filter to detect hx-request header and conditional logic in the @layout file?

    1
    1. Responding to virimchi-m
      @tomgobich

      Hi virimchi-m!

      Yep, you could absolutely do that! If the HX-Request header is there then HTMX sent the request, so you can use that to conditionally determine whether to render your layout or not. If needed you can also use the target, via the HX-Target header, to determine if the layout needs rerendered.

      Alternatively, you could put the contents you want to render within a component, very similar to how we did it in this series with our post_list then render that component directly!

      <ul>
        @each (post in posts)
          <li>{{ post.title }}</li>
        @endeach
      </ul>
      Copied!
      • resources
      • views
      • components
      • post
      • list.edge

      Then, we can use this component within the page:

      @layout()
        @!post.filter()
        @!post.list({ posts }) {{-- 👈 renders the list for the page --}}
      @end
      Copied!
      • resources
      • views
      • pages
      • posts
      • index.edge

      We can conditionally render it directly from our controller.

      export default class PostController {
        async index({ view, request }: HttpContext) {
          const isHtmx = !!request.header('HX-Request')
          const posts = [/* ... */]
         
          return isHtmx
            ? view.render('components/post/list', { posts })
            : view.render('pages/posts/index', { posts })
        }
      }
      Copied!

      0