Htmx

Struct Htmx 

Source
pub struct Htmx {
    pub is_htmx: bool,
    pub boosted: bool,
    pub history_restore_request: bool,
    /* private fields */
}
Expand description

Provides access to htmx request information and methods for setting htmx response headers.

The Htmx struct serves two main purposes:

  1. As an extractor, providing information about the current htmx request
  2. For managing htmx response headers

§Request Information

Access information about the current request:

use actix_web::{get, HttpResponse, Responder};
use actix_htmx::Htmx;

#[get("/")]
async fn handler(htmx: Htmx) -> impl Responder {
    if htmx.is_htmx {
        // This is an htmx request
        println!("Target element: {}", htmx.target().unwrap_or_default());
        println!("Trigger element: {}", htmx.trigger().unwrap_or_default());
    }
    // ...
    HttpResponse::Ok()
}

§Response Headers

Set htmx response headers for client-side behaviour:

use actix_web::{post, HttpResponse, Responder};
use actix_htmx::{Htmx, SwapType, TriggerPayload, TriggerType};
use serde_json::json;

#[post("/create")]
async fn create(htmx: Htmx) -> impl Responder {
    // Trigger a client-side event
    let payload = TriggerPayload::json(json!({ "id": 123 })).unwrap();
    htmx.trigger_event(
        "itemCreated",
        Some(payload),
        Some(TriggerType::Standard)
    );

    // Change how content is swapped
    htmx.reswap(SwapType::OuterHtml);

    // Redirect after the request
    htmx.redirect("/items");

    // ...
    HttpResponse::Ok()
}

Fields§

§is_htmx: bool

True if the request was made by htmx (has the hx-request header)

§boosted: bool

True if the request was made by a boosted element (has the hx-boosted header)

§history_restore_request: bool

True if this is a history restore request (has the hx-history-restore-request header)

Implementations§

Source§

impl Htmx

Source

pub fn new(req: &ServiceRequest) -> Htmx

Source

pub fn current_url(&self) -> Option<String>

Get the current URL from the hx-current-url header.

This header is sent by htmx and contains the current URL of the page.

Source

pub fn prompt(&self) -> Option<String>

Get the user’s response to an hx-prompt from the hx-prompt header.

This header contains the user’s input when an htmx request includes a prompt.

Source

pub fn target(&self) -> Option<String>

Get the ID of the target element from the hx-target header.

This header contains the ID of the element that will be updated with the response.

Source

pub fn trigger(&self) -> Option<String>

Get the ID of the element that triggered the request from the hx-trigger header.

This header contains the ID of the element that initiated the htmx request.

Source

pub fn trigger_name(&self) -> Option<String>

Get the name of the element that triggered the request from the hx-trigger-name header.

This header contains the name attribute of the element that initiated the htmx request.

Source

pub fn trigger_event( &self, name: impl Into<String>, payload: Option<TriggerPayload>, trigger_type: Option<TriggerType>, )

Trigger a custom JavaScript event on the client side.

This method allows you to trigger custom events that can be listened to with JavaScript. Events can include optional data and can be triggered at different points in the htmx lifecycle.

§Arguments
  • name - The name of the event to trigger
  • payload - Optional data to send with the event (typically JSON)
  • trigger_type - When to trigger the event (defaults to Standard)
§Example
use actix_htmx::{Htmx, TriggerPayload, TriggerType};

fn handler(htmx: Htmx) {
    // Simple event without data
    htmx.trigger_event("item-deleted", None, None);

    // Event with JSON data
    let payload = TriggerPayload::json(serde_json::json!({
        "message": "Success!",
        "type": "info"
    })).unwrap();

    htmx.trigger_event(
        "notification",
        Some(payload),
        Some(TriggerType::Standard)
    );
}
Source

pub fn redirect(&self, path: impl Into<String>)

Redirect to a new page with a full page reload.

This sets the hx-redirect header, which causes htmx to perform a client-side redirect to the specified URL with a full page reload.

Source

pub fn redirect_with_swap(&self, path: impl Into<String>)

Redirect to a new page using htmx (no full page reload).

This sets the hx-location header, which causes htmx to make a new request to the specified URL and swap the response into the current page.

Source

pub fn redirect_with_location(&self, location: HxLocation)

Redirect using a fully customized HX-Location object.

This lets you control additional behaviour like target selectors, swap strategies, or custom values for the follow-up request. Build the payload with HxLocation.

Source

pub fn refresh(&self)

Refresh the current page.

This sets the hx-refresh header, which causes htmx to refresh the entire page.

Source

pub fn push_url(&self, path: impl Into<String>)

Update the browser URL without causing a navigation.

This sets the hx-push-url header, which updates the browser’s address bar and adds an entry to the browser history.

Source

pub fn replace_url(&self, path: impl Into<String>)

Replace the current URL in the browser history.

This sets the hx-replace-url header, which updates the browser’s address bar without adding a new entry to the browser history.

Source

pub fn reswap(&self, swap_type: SwapType)

Change how htmx swaps content into the target element.

This sets the hx-reswap header, which overrides the default swap behaviour for this response.

Source

pub fn retarget(&self, selector: impl Into<String>)

Change the target element for content swapping.

This sets the hx-retarget header, which changes which element the response content will be swapped into.

Source

pub fn reselect(&self, selector: impl Into<String>)

Select specific content from the response to swap.

This sets the hx-reselect header, which allows you to select a subset of the response content to swap into the target.

Trait Implementations§

Source§

impl Clone for Htmx

Source§

fn clone(&self) -> Htmx

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl FromRequest for Htmx

Source§

type Error = Error

The associated error which can be returned.
Source§

type Future = Ready<Result<Htmx, Error>>

Future that resolves to a Self. Read more
Source§

fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future

Create a Self from request parts asynchronously.
Source§

fn extract(req: &HttpRequest) -> Self::Future

Create a Self from request head asynchronously. Read more

Auto Trait Implementations§

§

impl Freeze for Htmx

§

impl !RefUnwindSafe for Htmx

§

impl !Send for Htmx

§

impl !Sync for Htmx

§

impl Unpin for Htmx

§

impl !UnwindSafe for Htmx

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more