### Trigger HTMX Events with Axum Source: https://docs.rs/axum-htmx/latest/axum_htmx/index Shows how to use the HxResponseTrigger responder to trigger HTMX events on the client-side. It includes examples of triggering multiple events and triggering events with associated JSON data using the serde feature. ```rust use axum_htmx::HxResponseTrigger; // When we load our page, we will trigger any event listeners for "my-event. async fn index() -> (HxResponseTrigger, &'static str) { // Note: As HxResponseTrigger only implements `IntoResponseParts`, we must // return our trigger first here. ( HxResponseTrigger::normal(["my-event", "second-event"]), "Hello, world!", ) } ``` ```rust use serde_json::json; // Note that we are using `HxResponseTrigger` from the `axum_htmx::serde` module // instead of the root module. use axum_htmx::{HxEvent, HxResponseTrigger}; async fn index() -> (HxResponseTrigger, &'static str) { let event = HxEvent::new_with_data( "my-event", // May be any object that implements `serde::Serialize` json!({"level": "info", "message": { "title": "Hello, world!", "body": "This is a test message.", }}) ) .unwrap(); // Note: As HxResponseTrigger only implements `IntoResponseParts`, we must // return our trigger first here. (HxResponseTrigger::normal([event]), "Hello, world!") } ``` -------------------------------- ### Implement HTMX Request Guards in Axum Source: https://docs.rs/axum-htmx/latest/axum_htmx/index Illustrates how to use the HxRequestGuardLayer to protect Axum routes, ensuring that only HTMX requests are processed. Examples show default behavior (redirecting on non-HTMX) and custom redirect routes. ```rust use axum::Router; use axum_htmx::HxRequestGuardLayer; fn router_one() -> Router { Router::new() // Redirects to "/" if the HX-Request header is not present .layer(HxRequestGuardLayer::default()) } fn router_two() -> Router { Router::new() .layer(HxRequestGuardLayer::new("/redirect-to-this-route")) } ``` -------------------------------- ### Define VaryHxTarget Struct for HX-Target Header Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.VaryHxTarget Defines the `VaryHxTarget` struct, which represents the `Vary: HX-Target` header. This is useful for handlers that need to respond differently based on the `HX-Target` request header, primarily for GET requests to manage caching. It requires no external dependencies beyond the axum-htmx library. ```rust pub struct VaryHxTarget; ``` -------------------------------- ### Run All Axum HTMX Tests with Features Source: https://docs.rs/axum-htmx/latest/axum_htmx/index Provides the command to execute all tests for the axum-htmx crate, including tests for all enabled feature flags. This is useful for verifying functionality across different configurations. ```bash cargo +nightly test --all-features ``` -------------------------------- ### Create HxLocation with Options (Serde Feature) Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxLocation Allows creating an HxLocation with additional options, specifically when the 'serde' feature is enabled. The `from_str_with_options` function and the `From<(&'a str, LocationOptions)>` trait implementation facilitate this. ```rust pub fn from_str_with_options( uri: impl AsRef, options: LocationOptions, ) -> Self ``` ```rust fn from((uri, options): (&'a str, LocationOptions)) -> Self ``` -------------------------------- ### Create HxLocation from URI Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxLocation Provides methods to create an HxLocation instance. `from_str` takes a URI and sets it as the location. The `From<&'a str>` trait implementation offers an alternative way to achieve the same. ```rust pub fn from_str(uri: impl AsRef) -> Self ``` ```rust fn from(uri: &'a str) -> Self ``` -------------------------------- ### VaryHxTriggerName Responder Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.VaryHxTriggerName The `VaryHxTriggerName` struct is a responder that adds the `Vary: HX-Trigger-Name` header to the response. This is useful when your handler's response logic depends on the `HX-Trigger-Name` request header, particularly for GET requests which are often cached. ```APIDOC ## Struct VaryHxTriggerName ### Description The `Vary: HX-Trigger-Name` header. You may want to add this header to the response if your handler responds differently based on the `HX-Trigger-Name` request header. You probably need this only for `GET` requests, as other HTTP methods are not cached by default. See https://htmx.org/docs/#caching for more information. ### Method (Implicitly used with `IntoResponseParts`) ### Endpoint (Used within an axum route handler) ### Parameters None ### Request Example (Not applicable for this responder) ### Response #### Success Response (200) - **Headers**: Includes `Vary: HX-Trigger-Name` if the responder is used. #### Response Example (The effect is adding a header to the response, not a specific body structure) ``` -------------------------------- ### HxResponseTrigger Conversions (Rust) Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxResponseTrigger Shows how `HxResponseTrigger` can be created from tuples and how it implements `From` and `TryFrom` traits for conversions, enabling flexible integration with other parts of the Axum framework. ```rust impl From<(TriggerMode, T)> for HxResponseTrigger where T: IntoIterator, T::Item: Into ``` ```rust impl TryFrom for T where U: Into ``` ```rust impl TryInto for T where U: TryFrom ``` -------------------------------- ### Define VaryHxTrigger Struct in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.VaryHxTrigger Defines the VaryHxTrigger struct, used to set the 'Vary: HX-Trigger' header. This is useful when a handler needs to respond differently based on the HX-Trigger request header, particularly for GET requests to manage caching. ```rust pub struct VaryHxTrigger; ``` -------------------------------- ### Implement Clone for AutoVaryMiddleware (Rust) Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.AutoVaryMiddleware Provides the ability to clone instances of AutoVaryMiddleware. This implementation allows for creating duplicate middleware instances, which is useful for scenarios where the middleware state needs to be replicated. It includes methods for both `clone` and `clone_from`. ```Rust impl Clone for AutoVaryMiddleware { fn clone(&self) -> AutoVaryMiddleware fn clone_from(&mut self, source: &Self) } ``` -------------------------------- ### Define VaryHxTarget Struct Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.VaryHxTarget Defines the `VaryHxTarget` struct, which represents the `Vary: HX-Target` header. This struct is useful for handlers that need to vary their responses based on the `HX-Target` request header, particularly for GET requests to manage caching effectively. ```rust pub struct VaryHxTarget; ``` -------------------------------- ### Create HxLocation with Options from URI String in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.HxLocation Creates an HxLocation instance with additional options by parsing a given URI string. This function requires the 'serde' feature flag to be enabled. ```rust pub fn from_str_with_options( uri: impl AsRef, options: LocationOptions, ) -> Self ``` -------------------------------- ### Rust Implementation of Debug for LocationOptions Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.LocationOptions Illustrates the Debug trait implementation for LocationOptions, enabling formatted output for debugging purposes. This is crucial for inspecting the state of LocationOptions during development. ```rust impl Debug for LocationOptions { fn fmt(&self, f: &mut Formatter<'_>) -> Result // ... } ``` -------------------------------- ### Define VaryHxTriggerName Responder in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.VaryHxTriggerName The `VaryHxTriggerName` struct is used to add the 'Vary: HX-Trigger-Name' header to responses. This is useful when a handler's response varies based on the 'HX-Trigger-Name' request header, typically for GET requests to influence caching. It implements `IntoResponseParts` to integrate with Axum's response handling. ```rust pub struct VaryHxTriggerName; impl IntoResponseParts for VaryHxTriggerName { type Error = HxError; fn into_response_parts(self, mut res: ResponseParts) -> Result { res.headers.insert("Vary", HeaderValue::from_static("HX-Trigger-Name")); Ok(res) } } ``` -------------------------------- ### Define VaryHxTriggerName Struct for HTTP Header Caching Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.VaryHxTriggerName Defines the VaryHxTriggerName struct, which represents the 'Vary: HX-Trigger-Name' HTTP header. This is useful for handlers that need to vary their responses based on the HX-Trigger-Name request header, primarily for GET requests to control caching. It ensures that responses are cached correctly according to HTMX caching guidelines. ```rust pub struct VaryHxTriggerName; ``` -------------------------------- ### Create HxEvent Instance in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxEvent Provides methods to create new HxEvent instances. `new` creates an event without data, while `new_with_data` creates an event with associated serializable data. The latter requires the 'serde' feature and returns a Result due to potential serialization errors. ```rust /// Creates new event with no associated data. pub fn new(name: impl AsRef) -> Self ``` ```rust /// Creates new event with data. /// Available on **crate feature`serde`** only. pub fn new_with_data( name: impl AsRef, data: T, ) -> Result ``` -------------------------------- ### Implement FromRequest for HxCurrentUrl in Axum Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxCurrentUrl Demonstrates the blanket implementation of FromRequest for HxCurrentUrl, which relies on the FromRequestParts implementation. This allows HxCurrentUrl to be used seamlessly in Axum's request extraction mechanism, abstracting away the parts-based extraction. ```Rust impl FromRequest for T where S: Send + Sync, T: FromRequestParts, { type Rejection = >::Rejection; fn from_request(req: Request, state: &S) -> impl Future> { // Delegates to FromRequestParts implementation unimplemented!() } } ``` -------------------------------- ### Implement Service for AutoVaryMiddleware (Rust) Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.AutoVaryMiddleware Implements the `Service` trait for `AutoVaryMiddleware`, enabling it to process incoming requests and return responses asynchronously. This is the core functionality for middleware in the Tower ecosystem. It defines associated types for Response, Error, and Future, and provides methods for `poll_ready` and `call`. ```Rust impl Service> for AutoVaryMiddleware where S: Service + Send + 'static, S::Future: Send + 'static, { type Response = >>::Response; type Error = >>::Error; type Future = Pin as Service>>::Response, as Service>>::Error, >> + Send>>; fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll>; fn call(&mut self, request: Request) -> Self::Future; } ``` -------------------------------- ### Rust Implementation of Clone for LocationOptions Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.LocationOptions Shows the implementation of the Clone trait for the LocationOptions struct. This allows for creating duplicate instances of LocationOptions, which is useful for managing state or passing options around. ```rust impl Clone for LocationOptions { fn clone(&self) -> LocationOptions // ... fn clone_from(&mut self, source: &Self) // ... } ``` -------------------------------- ### axum-htmx SwapOption Debug Implementation Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/enum.SwapOption Illustrates the `Debug` trait implementation for `SwapOption`, enabling formatted output for debugging purposes. This helps in inspecting the state of a `SwapOption` during development. ```rust impl Debug for SwapOption { fn fmt(&self, f: &mut Formatter<'_>) -> Result { // ... implementation details ... } } ``` -------------------------------- ### Implement Debug for HxRedirect in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxRedirect Allows HxRedirect instances to be formatted for debugging output. This is crucial for inspecting the state of HxRedirect during development and troubleshooting. ```rust impl Debug for HxRedirect { fn fmt(&self, f: &mut Formatter<'_>) -> Result { // Implementation details... } } ``` -------------------------------- ### Rust Implementation of Default for LocationOptions Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.LocationOptions Demonstrates the Default trait implementation for LocationOptions, providing a default value for the struct. This simplifies the creation of LocationOptions when specific configurations are not immediately required. ```rust impl Default for LocationOptions { fn default() -> LocationOptions // ... } ``` -------------------------------- ### Create HxResponseTrigger (Rust) Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxResponseTrigger Provides methods for creating `HxResponseTrigger` instances. `new` creates a trigger with a specified mode and events. `normal`, `after_settle`, and `after_swap` are convenience functions for creating triggers with specific modes. ```rust pub fn new>( mode: TriggerMode, events: impl IntoIterator, ) -> Self ``` ```rust pub fn normal>(events: impl IntoIterator) -> Self ``` ```rust pub fn after_settle>( events: impl IntoIterator, ) -> Self ``` ```rust pub fn after_swap>(events: impl IntoIterator) -> Self ``` -------------------------------- ### HxResponseTrigger Response Handling (Rust) Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxResponseTrigger Demonstrates the `IntoResponseParts` implementation for `HxResponseTrigger`. This allows it to be seamlessly integrated into Axum responses, specifically for setting the `HX-Trigger*` headers. ```rust impl IntoResponseParts for HxResponseTrigger where Self: Send, { type Error = HxError; fn into_response_parts(self, res: ResponseParts) -> Result"; } ] } ] } ``` ``` -------------------------------- ### LocationOptions Struct Definition Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.LocationOptions The LocationOptions struct provides comprehensive configuration for HX-Location header responses in HTMX. It allows specification of request source, triggering events, response handlers, target elements, swap options, submission values, and custom headers for advanced client-side navigation control. ```APIDOC ## LocationOptions Struct ### Description Provides advanced configuration options for the HX-Location header in HTMX responses. This struct enables fine-grained control over how HTMX handles location-based navigation and response processing. ### Module `axum_htmx::responders` ### Availability Available with the `serde` crate feature enabled. ### Structure Definition ```rust pub struct LocationOptions { pub source: Option, pub event: Option, pub handler: Option, pub target: Option, pub swap: Option, pub values: Option, pub headers: Option, pub non_exhaustive: (), } ``` ### Fields #### source - **Type**: `Option` - **Description**: The source element of the request. Identifies which element triggered the HTMX request. #### event - **Type**: `Option` - **Description**: An event that triggered the request. Specifies which event (e.g., click, change) initiated the action. #### handler - **Type**: `Option` - **Description**: A callback function that will handle the response HTML. Allows custom processing of the server response. #### target - **Type**: `Option` - **Description**: The target element where the response will be swapped. Specifies which DOM element receives the response content. #### swap - **Type**: `Option` - **Description**: Defines how the response will be swapped in relative to the target element (e.g., innerHTML, outerHTML, beforeBegin). #### values - **Type**: `Option` - **Description**: Values to submit with the request. Contains data that will be sent alongside the HTMX request. #### headers - **Type**: `Option` - **Description**: Custom headers to submit with the request. Allows specification of additional HTTP headers. #### non_exhaustive - **Type**: `()` - **Description**: Marker field for non-exhaustive struct pattern matching, allowing future field additions without breaking changes. ### Trait Implementations #### Clone - Returns a duplicate of the LocationOptions instance. #### Debug - Implements formatted debug output using `fmt::Debug`. #### Default - Provides default instance with all fields set to `None`. #### Serialize - Implements Serde serialization for converting LocationOptions to JSON or other formats. ### Auto Trait Implementations - `Freeze`: Can be safely frozen as immutable - `RefUnwindSafe`: Safe to use across panic unwind boundaries - `Send`: Safe to send across thread boundaries - `Sync`: Safe to share across thread boundaries - `Unpin`: No special pinning requirements - `UnwindSafe`: Safe during panic unwinding ### Usage Example ```rust use axum_htmx::responders::LocationOptions; use serde_json::json; let location_options = LocationOptions { source: Some("button-id".to_string()), event: Some("click".to_string()), handler: Some("myHandler".to_string()), target: Some("#target-div".to_string()), swap: None, values: Some(json!({ "key": "value" })), headers: Some(json!({ "Authorization": "Bearer token" })), non_exhaustive: (), }; ``` ``` -------------------------------- ### Create Normal HxResponseTrigger - Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.HxResponseTrigger Factory method that creates an HxResponseTrigger with TriggerMode::Normal, triggering events immediately. Simplifies common use case without requiring explicit mode specification. ```rust pub fn normal>( events: impl IntoIterator, ) -> Self ``` -------------------------------- ### Implement From for HxRefresh Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxRefresh Provides an implementation to create an HxRefresh struct directly from a boolean value. This allows for easy conversion when setting the HX-Refresh header. ```rust impl From for HxRefresh { fn from(value: bool) -> Self { // Implementation details } } ``` -------------------------------- ### Create HxLocation from URI String in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.HxLocation Creates an HxLocation instance by parsing a given URI string. This is a basic constructor for the HxLocation struct. ```rust pub fn from_str(uri: impl AsRef) -> Self ``` -------------------------------- ### Rust Implementation of Serialize for LocationOptions Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.LocationOptions Details the Serialize trait implementation for LocationOptions, enabling the struct to be serialized into various formats. This is particularly relevant when 'serde' feature is enabled, allowing the struct to be sent over networks or stored. ```rust impl Serialize for LocationOptions { fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error> where __S: Serializer, // ... } ``` -------------------------------- ### Implement From for HxReswap in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxReswap Enables conversion from a SwapOption type into an HxReswap struct. This implementation simplifies the creation of HxReswap instances by allowing direct use of SwapOption values. ```rust impl From for HxReswap { fn from(value: SwapOption) -> Self; } ``` -------------------------------- ### axum-htmx SwapOption Clone Implementation Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/enum.SwapOption Details the `Clone` trait implementation for `SwapOption`, allowing instances of the enum to be duplicated. This is essential for passing swap options around without ownership issues. ```rust impl Clone for SwapOption { fn clone(&self) -> SwapOption { // ... implementation details ... } fn clone_from(&mut self, source: &Self) { // ... implementation details ... } } ``` -------------------------------- ### Rust Struct Definition for LocationOptions Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.LocationOptions Defines the LocationOptions struct used to configure the HX-Location header in axum-htmx. It includes optional fields for source, event, handler, target, swap, values, and headers. This struct requires the 'serde' feature flag to be enabled. ```rust pub struct LocationOptions { pub source: Option, pub event: Option, pub handler: Option, pub target: Option, pub swap: Option, pub values: Option, pub headers: Option, pub non_exhaustive: (), } ``` -------------------------------- ### Implement From<(&str, LocationOptions)> for HxLocation in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.HxLocation Implements the From<(&str, LocationOptions)> trait for HxLocation, allowing conversion from a tuple containing a string slice and LocationOptions. This requires the 'serde' feature flag. ```rust fn from((uri, options): (&'a str, LocationOptions)) -> Self ``` -------------------------------- ### Implement Debug for VaryHxTarget Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.VaryHxTarget Implements the `Debug` trait for `VaryHxTarget`, enabling formatted debugging output. The `fmt` method allows the struct to be printed using debug formatting, which is essential for development and troubleshooting. ```rust impl Debug for VaryHxTarget { fn fmt(&self, f: &mut Formatter<'_>) -> Result; } ``` -------------------------------- ### axum-htmx SwapOption Serialize Implementation Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/enum.SwapOption Covers the `Serialize` trait implementation for `SwapOption` using the Serde library. This allows `SwapOption` values to be serialized into various formats, such as JSON. ```rust impl Serialize for SwapOption { fn serialize(&self, serializer: S) -> Result where S: Serializer, { // ... implementation details ... } } ``` -------------------------------- ### Implement Debug for VaryHxRequest Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.VaryHxRequest Implements the Debug trait for VaryHxRequest, enabling formatted output for debugging purposes using the `fmt` method. ```Rust impl Debug for VaryHxRequest { fn fmt(&self, f: &mut Formatter<'_>) -> Result { // ... implementation ... } } ``` -------------------------------- ### Implement Clone for VaryHxRequest Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.VaryHxRequest Provides implementations for the Clone trait for the VaryHxRequest struct, allowing instances to be duplicated. This includes the `clone` and `clone_from` methods. ```Rust impl Clone for VaryHxRequest { fn clone(&self) -> VaryHxRequest { // ... implementation ... } fn clone_from(&mut self, source: &Self) { // ... implementation ... } } ``` -------------------------------- ### Implement Clone for HxRedirect in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxRedirect Provides the ability to clone HxRedirect instances. This is useful when the redirect information needs to be duplicated or passed around multiple times without moving ownership. ```rust impl Clone for HxRedirect { fn clone(&self) -> HxRedirect { // Implementation details... } fn clone_from(&mut self, source: &Self) { // Implementation details... } } ``` -------------------------------- ### Implement From for HxEvent in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxEvent Illustrates the `From` trait implementation, allowing `HxEvent` to be created directly from any type `N` that implements `AsRef`. This provides a convenient way to construct `HxEvent` instances using string-like inputs. ```rust impl> From for HxEvent { fn from(name: N) -> Self; } ``` -------------------------------- ### Blanket Implementations for Generic Types in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxPushUrl Showcases blanket implementations of various traits for generic types that satisfy specific bounds. These include implementations for Any, Borrow, BorrowMut, CloneToUninit, From, FromRef, Into, ToOwned, TryFrom, and TryInto. ```rust impl Any for T where T: 'static + ?Sized impl Borrow for T where T: ?Sized impl BorrowMut for T where T: ?Sized impl CloneToUninit for T where T: Clone impl From for T impl FromRef for T where T: Clone impl Into for T where U: From impl ToOwned for T where T: Clone impl TryFrom for T where U: Into impl TryInto for T where U: TryFrom ``` -------------------------------- ### Implement Clone for HxReswap in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxReswap Provides implementations for the Clone trait for the HxReswap struct. This allows creating duplicate instances of HxReswap, ensuring that the swap option can be copied. It includes methods for both direct cloning and clone-from. ```rust impl Clone for HxReswap { fn clone(&self) -> HxReswap; fn clone_from(&mut self, source: &Self); } ``` -------------------------------- ### Implement From<&str> for HxRedirect in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxRedirect Provides an implementation for converting a string slice (&str) into an HxRedirect struct. This allows for easy creation of HxRedirect instances from literal strings or string variables. ```rust impl<'a> From<&'a str> for HxRedirect { fn from(value: &'a str) -> Self { // Implementation details... } } ``` -------------------------------- ### HxTrigger Vary Response Header Convenience Method Source: https://docs.rs/axum-htmx/latest/axum_htmx/extractors/struct.HxTrigger Provides a convenience method `vary_response` for the HxTrigger struct. This method is used to create the corresponding `Vary` response header, which is important for caching mechanisms in HTTP. ```rust pub fn vary_response() -> VaryHxTrigger ``` -------------------------------- ### Implement Debug for HxReselect (Rust) Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxReselect Implements the Debug trait for HxReselect, enabling formatted output for debugging purposes. The `fmt` method is used to write the formatter's buffer. ```rust impl Debug for HxReselect Source #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more ``` -------------------------------- ### Create VaryHxTarget Header (Rust) Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxTarget Provides a convenience method `vary_response` on the HxTarget struct to create the corresponding `Vary` response header. This is useful for ensuring proper caching behavior when dealing with HTMX partial updates. ```rust pub fn vary_response() -> VaryHxTarget ``` -------------------------------- ### HxRequestGuard Service Implementation (Rust) Source: https://docs.rs/axum-htmx/latest/axum_htmx/guard/struct.HxRequestGuard Details the `Service` trait implementation for `HxRequestGuard` in Rust, which is crucial for its role as a Tower service. It defines the `Response`, `Error`, `Future` types and the `poll_ready` and `call` methods for processing requests. ```rust impl<'a, S, T, U> Service> for HxRequestGuard<'a, S> where S: Service, Response = Response>, U: Default, type Response = >>::Response type Error = >>::Error type Future = ResponseFuture<'a, >>::Future> fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> fn call(&mut self, req: Request) -> Self::Future ``` -------------------------------- ### Implement IntoResponseParts for HxPushUrl Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.HxPushUrl Enables HxPushUrl to be used directly in Axum's response handling by implementing the IntoResponseParts trait. This allows the HX-Push-Url header to be set automatically when HxPushUrl is returned from an Axum handler. ```rust impl IntoResponseParts for HxPushUrl { type Error = HxError; fn into_response_parts(self, res: ResponseParts) -> Result; } ``` -------------------------------- ### Rust Struct Definition and Constructor for HxRequestGuardLayer Source: https://docs.rs/axum-htmx/latest/axum_htmx/guard/struct.HxRequestGuardLayer Defines the HxRequestGuardLayer struct used for guarding requests based on the HX-Request header. The `new` function initializes the guard layer with a redirect target. ```rust pub struct HxRequestGuardLayer<'a> { /* private fields */ } pub fn new(redirect_to: &'a str) -> Self ``` -------------------------------- ### Implement Clone for LocationOptions in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.LocationOptions Provides implementations for the `Clone` trait for the `LocationOptions` struct in Rust. This allows creating duplicate instances of `LocationOptions` and performing copy-assignment. ```rust impl Clone for LocationOptions fn clone(&self) -> LocationOptions fn clone_from(&mut self, source: &Self) ``` -------------------------------- ### Extract HX-Boosted Header in Axum Source: https://docs.rs/axum-htmx/latest/axum_htmx/index Demonstrates how to use the HxBoosted extractor to check the 'HX-Boosted' header. This is useful for conditionally rendering different templates (e.g., full vs. partial) based on whether the request is boosted by HTMX. ```rust use axum::response::IntoResponse; use axum_htmx::HxBoosted; async fn get_index(HxBoosted(boosted): HxBoosted) -> impl IntoResponse { if boosted { // Send a template extending from _partial.html } else { // Send a template extending from _base.html } } ``` -------------------------------- ### Implement IntoResponseParts for HxPushUrl in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxPushUrl Enables HxPushUrl to be used as part of an HTTP response. This implementation allows setting response parts, including the HX-Push-Url header, and defines a potential error type for conversion failures. ```rust impl IntoResponseParts for HxPushUrl { type Error = HxError; fn into_response_parts(self, res: ResponseParts) -> Result; } ``` -------------------------------- ### Create After-Swap HxResponseTrigger - Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.HxResponseTrigger Factory method that creates an HxResponseTrigger with TriggerMode::AfterSwap, delaying event triggering until after content is swapped. Allows for timing-controlled event firing. ```rust pub fn after_swap>( events: impl IntoIterator, ) -> Self ``` -------------------------------- ### Implement From<&str> for HxLocation in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.HxLocation Implements the From<&str> trait for HxLocation, enabling conversion from string slices to HxLocation instances. This provides a convenient way to create HxLocation objects. ```rust fn from(uri: &'a str) -> Self ``` -------------------------------- ### Implement From Trait for HxReselect Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.HxReselect Implements the From trait to allow conversion from any type that can be converted into a String. This provides flexible initialization of HxReselect instances from various string-like types. ```rust impl> From for HxReselect { fn from(value: T) -> Self { HxReselect(value.into()) } } ``` -------------------------------- ### HxRequestGuard Clone Implementation (Rust) Source: https://docs.rs/axum-htmx/latest/axum_htmx/guard/struct.HxRequestGuard Demonstrates the `Clone` trait implementation for `HxRequestGuard` in Rust. This allows for creating duplicate instances of the guard, which can be useful in scenarios where the service needs to be shared or reused. ```rust impl<'a, S: Clone> Clone for HxRequestGuard<'a, S> fn clone(&self) -> HxRequestGuard<'a, S> fn clone_from(&mut self, source: &Self) ``` -------------------------------- ### AutoVaryMiddleware Struct Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.AutoVaryMiddleware Tower service middleware for managing automatic Vary headers in HTMX responses. This middleware intercepts requests and responses to add appropriate Vary headers based on HTMX request detection. ```APIDOC ## AutoVaryMiddleware ### Description Tower service middleware that automatically manages HTTP Vary headers for HTMX requests. This struct implements the Tower Service trait for generic service types. ### Availability - **Feature Flag**: `auto-vary` (required) - **Crate**: `axum_htmx` ### Struct Definition ```rust pub struct AutoVaryMiddleware { /* private fields */ } ``` ### Generic Parameters - **S**: Service type that implements `Service + Send + 'static` ### Trait Implementations #### Clone - **Method**: `clone(&self) -> AutoVaryMiddleware` - **Requirement**: S must implement Clone - **Description**: Returns a duplicate of the middleware instance #### Service> - **Associated Type Response**: Response type from the inner service - **Associated Type Error**: Error type from the inner service - **Associated Type Future**: Pinned boxed future with Send bound ##### Methods **poll_ready** - **Signature**: `fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll>` - **Description**: Returns `Poll::Ready(Ok(()))` when the service is ready to process requests **call** - **Signature**: `fn call(&mut self, request: Request) -> Self::Future` - **Description**: Processes the incoming request asynchronously and returns the response - **Returns**: Pinned boxed future that resolves to the response or error ### Auto Trait Implementations - **Freeze**: Implemented when S is Freeze - **RefUnwindSafe**: Implemented when S is RefUnwindSafe - **Send**: Implemented when S is Send - **Sync**: Implemented when S is Sync - **Unpin**: Implemented when S is Unpin - **UnwindSafe**: Implemented when S is UnwindSafe ### Usage Example ```rust // AutoVaryMiddleware is typically used with AutoVaryLayer // to automatically add Vary headers to responses for HTMX requests let middleware = AutoVaryMiddleware { /* ... */ }; ``` ### Requirements - Requires `auto-vary` feature flag to be enabled - Inner service S must be Send + 'static - Future produced by S must be Send + 'static ``` -------------------------------- ### HxTrigger FromRequest Implementation Source: https://docs.rs/axum-htmx/latest/axum_htmx/extractors/struct.HxTrigger Shows the implementation of the `FromRequest` trait for the HxTrigger struct. This is a more general way to implement request extraction in Axum, allowing HxTrigger to be extracted from a full `Request` object. It relies on the `FromRequestParts` implementation. ```rust impl FromRequest for T where S: Send + Sync, T: FromRequestParts, { type Rejection = >::Rejection; fn from_request(req: Request, state: &S) -> impl Future>::Rejection>> { // Implementation delegates to from_request_parts } } ``` -------------------------------- ### Implement Serialize for LocationOptions in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.LocationOptions Implements the `Serialize` trait for the `LocationOptions` struct in Rust, enabling serialization of the struct into various formats using Serde. ```rust impl Serialize for LocationOptions fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error> where __S: Serializer, ``` -------------------------------- ### Implement Clone for HxTriggerName (Rust) Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxTriggerName Shows the `Clone` trait implementation for `HxTriggerName`. This enables creating copies of `HxTriggerName` instances, which is useful for scenarios where the header value might need to be accessed multiple times or passed around. ```rust impl Clone for HxTriggerName { fn clone(&self) -> HxTriggerName { // Implementation details for cloning } fn clone_from(&mut self, source: &Self) { // Implementation details for clone_from } } ``` -------------------------------- ### Implement IntoResponseParts for VaryHxRequest Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.VaryHxRequest Implements the IntoResponseParts trait for VaryHxRequest, allowing it to be converted into parts of an HTTP response. This includes defining the associated `Error` type and the `into_response_parts` method for setting response headers. ```Rust impl IntoResponseParts for VaryHxRequest { type Error = HxError; fn into_response_parts(self, res: ResponseParts) -> Result { // ... implementation ... } } ``` -------------------------------- ### Implement Clone for HxRetarget in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxRetarget Demonstrates the implementation of the Clone trait for the HxRetarget struct. This allows for creating duplicate instances of HxRetarget, which is essential for scenarios where the retargeting information needs to be copied. ```rust impl Clone for HxRetarget { fn clone(&self) -> HxRetarget { HxRetarget(self.0.clone()) } fn clone_from(&mut self, source: &Self) { self.0.clone_from(&source.0); } } ``` -------------------------------- ### Axum HxRefresh Responder for Full Page Refresh Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.HxRefresh The HxRefresh struct in axum-htmx is used to set the 'HX-Refresh' header. When set to true, it instructs the client-side to perform a full page refresh. This responder is guaranteed not to fail. ```rust pub struct HxRefresh(pub bool); // Example usage within an Axum handler: // async fn my_handler() -> impl IntoResponse { // (StatusCode::OK, HxRefresh(true)) // } ``` -------------------------------- ### Implement IntoResponseParts for HxRedirect in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxRedirect Enables the HxRedirect struct to be used within the axum framework's response handling. This implementation allows HxRedirect to be directly returned from request handlers, setting the HX-Redirect header in the HTTP response. ```rust impl IntoResponseParts for HxRedirect { type Error = HxError; fn into_response_parts(self, mut res: ResponseParts) -> Result { // Implementation details... } } ``` -------------------------------- ### Implement IntoResponseParts for VaryHxTarget Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.VaryHxTarget Implements the `IntoResponseParts` trait for `VaryHxTarget`. This allows `VaryHxTarget` to be converted into parts of an HTTP response, enabling it to be directly used in axum route handlers to set response headers. ```rust impl IntoResponseParts for VaryHxTarget { type Error = HxError; fn into_response_parts( self, res: ResponseParts, ) -> Result; } ``` -------------------------------- ### Implement Default for LocationOptions in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.LocationOptions Provides the `Default` trait implementation for the `LocationOptions` struct in Rust, allowing for the creation of a default instance. ```rust impl Default for LocationOptions fn default() -> LocationOptions ``` -------------------------------- ### HxPrompt Extraction Logic in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxPrompt Demonstrates the asynchronous function `from_request_parts` which is crucial for extracting the HxPrompt from request parts. This function is part of the `FromRequestParts` trait implementation for `HxPrompt`. It handles the logic of checking for the 'HX-Prompt' header and returning it as an `Option`, with `Infallible` as the rejection type. ```rust async fn from_request_parts( parts: &mut Parts, _: &S, ) -> Result ``` -------------------------------- ### Implement Debug for VaryHxTrigger in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.VaryHxTrigger Implements the Debug trait for VaryHxTrigger, enabling formatted output for debugging purposes. This allows instances of VaryHxTrigger to be printed using the {:?} format specifier. ```rust impl Debug for VaryHxTrigger { fn fmt(&self, f: &mut Formatter<'_>) -> Result { f.debug_struct("VaryHxTrigger").finish() } } ``` -------------------------------- ### Define HxRefresh Struct for HX-Refresh Header Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxRefresh Defines the HxRefresh struct, which represents the HX-Refresh header. When set to true, it instructs the client-side to perform a full page refresh. This responder is guaranteed not to fail. ```rust pub struct HxRefresh(pub bool); ``` -------------------------------- ### Implement Clone for VaryHxTarget Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.VaryHxTarget Provides `Clone` trait implementations for the `VaryHxTarget` struct, allowing for the creation of duplicate values. This includes `clone` and `clone_from` methods. These implementations are standard for Rust structs that can be safely duplicated. ```rust impl Clone for VaryHxTarget { fn clone(&self) -> VaryHxTarget; fn clone_from(&mut self, source: &Self); } ``` -------------------------------- ### Implement IntoResponseParts for HxReselect (Rust) Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxReselect Implements the IntoResponseParts trait for HxReselect, enabling it to be used directly in response generation within the Axum framework. This allows setting response parts, including headers like HX-Reselect. ```rust impl IntoResponseParts for HxReselect Source #### type Error = HxError The type returned in the event of an error. Read more #### fn into_response_parts( self, res: ResponseParts, ) -> Result Set parts of the response ``` -------------------------------- ### Implement IntoResponseParts for HxReswap in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxReswap Allows HxReswap to be converted into parts of an HTTP response, specifically for use with the axum framework. This integration enables HxReswap to be directly returned from request handlers to set the HX-Reswap header. ```rust impl IntoResponseParts for HxReswap { type Error = Infallible; fn into_response_parts( self, res: ResponseParts, ) -> Result; } ``` -------------------------------- ### Implement Debug for LocationOptions in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.LocationOptions Implements the `Debug` trait for the `LocationOptions` struct in Rust, enabling formatted output for debugging purposes. ```rust impl Debug for LocationOptions fn fmt(&self, f: &mut Formatter<'_>) -> Result ``` -------------------------------- ### Implement From for HxReselect (Rust) Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxReselect Provides a generic From trait implementation for HxReselect, allowing conversion from any type `T` that can be converted into a String. This simplifies the creation of HxReselect instances. ```rust impl> From for HxReselect Source #### fn from(value: T) -> Self Converts to this type from the input type. ``` -------------------------------- ### Create VaryHxTriggerName Response Header (Rust) Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxTriggerName Provides a convenience method `vary_response` on the `HxTriggerName` struct. This method is used to create the corresponding `Vary` response header, ensuring proper caching and request handling when `HX-Trigger-Name` is involved. ```rust pub fn vary_response() -> VaryHxTriggerName ``` -------------------------------- ### Convert Tuple to HxResponseTrigger - Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.HxResponseTrigger Implements From trait to convert a tuple of (TriggerMode, events collection) into an HxResponseTrigger. Provides ergonomic conversion for creating triggers from tuple syntax. ```rust impl From<(TriggerMode, T)> for HxResponseTrigger where T: IntoIterator, T::Item: Into, { fn from((mode, events): (TriggerMode, T)) -> Self } ``` -------------------------------- ### HxPrompt Extractor for Axum HTMX Source: https://docs.rs/axum-htmx/latest/axum_htmx/extractors/struct.HxPrompt The HxPrompt struct is an extractor provided by axum-htmx to retrieve the value of the 'HX-Prompt' header. This header is set when a request originates from an element with the 'hx-prompt' attribute. The extractor returns an Option, providing None if the header is absent. It implements standard Rust traits like Clone and Debug, and integrates with Axum's request extraction mechanism. ```rust pub struct HxPrompt(pub Option); // Implementation details for FromRequestParts, Clone, Debug, etc. // ... impl FromRequestParts for HxPrompt where S: Send + Sync, { type Rejection = Infallible; async fn from_request_parts(parts: &mut Parts, _: &S) -> Result { // Logic to extract HX-Prompt header // ... Ok(HxPrompt(Some("user input".to_string()))) } } ``` -------------------------------- ### Create VaryHxTarget for Response Headers in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/extractors/struct.HxTarget Provides a convenience method to generate a VaryHxTarget, which is a `Vary` response header. This is useful for ensuring proper caching behavior when the HX-Target header influences the response. ```Rust pub fn vary_response() -> VaryHxTarget ``` -------------------------------- ### Implement Debug for HxReswap in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxReswap Implements the Debug trait for HxReswap, enabling formatted output for debugging purposes. This is crucial for inspecting the state of HxReswap during development and troubleshooting. ```rust impl Debug for HxReswap { fn fmt(&self, f: &mut Formatter<'_>) -> Result; } ``` -------------------------------- ### Create HxEvent with Name and Data in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.HxEvent Constructs a new HxEvent instance with a name and associated data. The data must be serializable, and this function requires the 'serde' feature flag. ```Rust pub fn new_with_data( name: impl AsRef, data: T, ) -> Result ``` -------------------------------- ### axum-htmx SwapOption Conversion to HxReswap Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/enum.SwapOption Shows how `SwapOption` enum variants can be converted into the `HxReswap` type, likely for direct use within axum-htmx response structures. ```rust impl From for HxReswap { fn from(value: SwapOption) -> Self { // ... implementation details ... } } ``` -------------------------------- ### Implement From<&str> for HxPushUrl in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/struct.HxPushUrl Allows conversion of a string slice (&str) into an HxPushUrl struct. This is a convenient way to create HxPushUrl instances from string literals or string slices. ```rust impl<'a> From<&'a str> for HxPushUrl { fn from(value: &'a str) -> Self; } ``` -------------------------------- ### Define HxReswap Struct with SwapOption Source: https://docs.rs/axum-htmx/latest/axum_htmx/responders/struct.HxReswap The HxReswap struct is a tuple struct that wraps a SwapOption value. It implements Clone, Debug, Copy, and can be converted from SwapOption. This responder integrates with Axum's response system to set the HX-Reswap header without failure. ```rust pub struct HxReswap(pub SwapOption); ``` -------------------------------- ### HxRequestGuard Debug Implementation (Rust) Source: https://docs.rs/axum-htmx/latest/axum_htmx/guard/struct.HxRequestGuard Shows the `Debug` trait implementation for `HxRequestGuard` in Rust. This enables the struct to be formatted for debugging purposes, allowing developers to inspect its state when needed. ```rust impl<'a, S: Debug> Debug for HxRequestGuard<'a, S> fn fmt(&self, f: &mut Formatter<'_>) -> Result ``` -------------------------------- ### Implement Error Handling for HxError in Rust Source: https://docs.rs/axum-htmx/latest/axum_htmx/enum.HxError Shows the implementation of standard Rust error handling traits for the HxError enum. This includes Debug, Display, and the core Error trait with methods like `source`, `description`, `cause`, and `provide`. ```rust impl Debug for HxError impl Display for HxError impl Error for HxError ```