Skip to main content

View

Struct View 

Source
pub struct View { /* private fields */ }
Expand description

A view to render with some data, created by view. It renders when it is sent as a response or when you call render.

As a response, it is 200 OK with text/html. When it fails to render, the response is the error page instead.

Implementations§

Source§

impl View

Source

pub fn with_input(self, request: &Request) -> View

Give the view the request’s input as old input, so the template’s old(..) helper reads it when rendering a form directly (such as a 422 fragment response without a redirect).

Laravel leaves out uploaded files, the top-level password, password_confirmation, and current_password fields, the fields given to Errors::dont_flash, and, once the request has been validated, every Password field at any depth, with its confirmation.

use laravel::http::{IntoResponse, Request, Response, StatusCode};
use laravel::validation::{Validate, ValidationError};
use laravel::view::{data, view};

#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct StorePost {
    #[validate(required)]
    title: String,
}

async fn store(request: Request) -> laravel::Result<Response> {
    let _form = match request.validate::<StorePost>().await {
        Ok(form) => form,
        Err(ValidationError::Invalid(errors)) => {
            return Ok(view("posts.create", data! {})
                .with_errors(errors)
                .with_input(&request)
                .fragment("form")
                .into_response()
                .with_status(StatusCode::UNPROCESSABLE_ENTITY));
        }
        Err(ValidationError::Failed(error)) => return Err(error),
    };

    Ok(Response::new("saved"))
}
Source§

impl View

Source

pub fn with_errors(self, errors: impl Borrow<InvalidInput>) -> View

Gives the view a form’s field messages as errors, in place of the messages the session flashed. Every view has an errors map, which is empty when there are no messages, so a template can always look up a field’s messages.

Messages for a named form, or for the form of the type the request validated, go in form_errors instead, under the form’s name. Templates read them with error("email", form="login").

async fn store(email: String) -> (StatusCode, View) {
    match check(&email) {
        Ok(()) => (StatusCode::OK, view("signup.done", ())),
        Err(errors) => (
            StatusCode::UNPROCESSABLE_ENTITY,
            view("signup.form", data! { email }).with_errors(errors).fragment("form"),
        ),
    }
}
Source§

impl View

Send a cookie with this response. A (name, value) pair uses the default attributes, and a Cookie sets its own. The cookie replaces any cookie that this response already sends with the same name, path, and domain.

use laravel::http::{Redirect, Response};

let response = Response::new("Saved").with_cookie(("theme", "dark"));
let redirect = Redirect::to("/").with_cookie(("theme", "dark"));

Remove a browser cookie by sending an expired cookie. A name uses the default path and domain. To match a custom path or domain, pass a Cookie. The cookie values that the current request returns stay unchanged.

use laravel::http::Response;
use laravel::cookie::Cookie;

let response = Response::new("Signed out")
    .without_cookie("remember")
    .without_cookie(Cookie::new("tour", "").path("/admin"));
Source

pub fn with_header<K, V>(self, name: K, value: V) -> View

Send a header with the response, replacing any header with the same name, including one the response would otherwise send:

use laravel::view::{View, view};

async fn report() -> View {
    view("reports.show", ()).with_header("cache-control", "no-store")
}

A name or value that isn’t a valid header turns the response into a 500 error when the response is sent.

Source

pub fn with_headers<K, V>( self, headers: impl IntoIterator<Item = (K, V)>, ) -> View

Send several headers with the response, such as .with_headers([("x-one", "1"), ("x-two", "2")]). Each header replaces any header with the same name, so when the list holds a name twice, the last value wins.

A name or value that isn’t a valid header turns the response into a 500 error when the response is sent.

Source

pub fn with_html(self, name: impl Into<String>, markup: Html) -> View

Gives the view markup to display without escaping, such as HTML rendered from trusted Markdown. The markup replaces any data with the same name.

async fn show() -> View {
    let body = render_markdown("# Hello");

    view("posts.show", data! { title => "Hello" }).with_html("body", body)
}
Source

pub fn fragment(self, block: impl Into<String>) -> View

Renders only the {% block %} named block, rather than the whole page, such as to replace part of a page from a JavaScript request.

async fn search(partial: bool) -> View {
    let results = vec!["Taylor"];
    let page = view("users.index", data! { results });

    if partial { page.fragment("results") } else { page }
}
Source

pub fn fragment_if(self, condition: bool, block: impl Into<String>) -> View

Renders only one block when condition is true, as in view(..).fragment_if(partial, "results").

Source

pub fn name(&self) -> &str

The view’s name.

Source

pub const fn data(&self) -> &ViewData

The view’s own data, without the data shared with every view.

Source

pub fn render(&self) -> Result<Html, Error>

Renders the view to HTML, with the shared data and the session’s form errors.

§Errors

Fails with a 500 when the view can’t be found, its data can’t be serialized or isn’t a map, or its engine fails to render it.

§Panics

Panics outside of the application, such as in a plain unit test.

Trait Implementations§

Source§

impl Clone for View

Source§

fn clone(&self) -> View

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for View

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl From<View> for EventData

Converts a view into event data, which renders the view when the event is sent.

Source§

fn from(view: View) -> EventData

Converts to this type from the input type.
Source§

impl From<View> for Body

Source§

fn from(view: View) -> Body

Converts to this type from the input type.
Source§

impl IntoResponse for View

Renders the view, or the error that kept the view from rendering. The view’s name and data stay on the response for assert_view_is in tests.

Source§

fn into_response(self) -> Response

Turn this into a Response. Read more
Send a cookie with this response, replacing any cookie the response already sends with the same name, path, and domain. Read more
Remove a browser cookie. Pass the cookie’s name, or a Cookie with the path and domain that set it. Read more
Source§

fn with_header<K, V>(self, name: K, value: V) -> Response

Send a header with the response, replacing any header with the same name. A name or value that isn’t a valid header makes the response a 500 error.
Source§

fn with_headers<K, V>( self, headers: impl IntoIterator<Item = (K, V)>, ) -> Response

Send several headers with the response, each replacing any header with the same name. A name or value that isn’t a valid header makes the response a 500 error.
Source§

impl ViewInternals for View

Source§

fn render_for_mail(&self, format: Format) -> Result<Html, Error>

Renders the view for an email, without the current request’s shared data, session, and form errors. Read more

Auto Trait Implementations§

§

impl Forget for View

§

impl Freeze for View
where *const u8 is !null: Freeze, PhantomData<u8>: Freeze, PhantomData<usize>: Freeze, PhantomData<Bucket<String, Value>>: Freeze, *const ArcInner<str> is !null: Freeze, PhantomData<ArcInner<str>>: Freeze, PhantomData<(String, Html)>: Freeze, *const [Pos] is !null: Freeze, PhantomData<[Pos]>: Freeze, PhantomData<Bucket<HeaderValue>>: Freeze, PhantomData<ExtraValue<HeaderValue>>: Freeze, *const ArcInner<Inner> is !null: Freeze, PhantomData<ArcInner<Inner>>: Freeze, &'static Location<'static>: Freeze,

§

impl Move for View

§

impl RefUnwindSafe for View

§

impl Send for View
where RawVecInner: Send, RawTable<usize>: Send, Arc<str>: Send, BoxRaw<[Pos]>: Send, Bytes: Send, Arc<Inner>: Send, &'static Location<'static>: Send,

§

impl Sync for View
where RawVecInner: Sync, RawTable<usize>: Sync, Arc<str>: Sync, BoxRaw<[Pos]>: Sync, Bytes: Sync, Arc<Inner>: Sync, Location<'static>: Sync,

§

impl Unpin for View
where *const u8 is !null: Unpin, Arc<str>: Unpin, Box<[Pos]>: Unpin, *const u8: Unpin, Align8<*mut ()>: Unpin, &'static Vtable: Unpin, Arc<Inner>: Unpin, &'static Location<'static>: Unpin,

§

impl UnsafeUnpin for View

§

impl UnwindSafe for View
where RawVecInner: UnwindSafe, NonNull<u8>: UnwindSafe, Arc<str>: UnwindSafe, BoxRaw<[Pos]>: UnwindSafe, *const u8: UnwindSafe, Align8<*mut ()>: UnwindSafe, &'static Vtable: UnwindSafe, Arc<Inner>: UnwindSafe, &'static Location<'static>: UnwindSafe,

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> ErasedDestructor for T
where T: 'static,

Source§

impl<T> Fake for T

Source§

fn fake<U>(&self) -> U
where Self: FakeBase<U>,

Source§

fn fake_with_rng<U, R>(&self, rng: &mut R) -> U
where R: RngExt + ?Sized, Self: FakeBase<U>,

Source§

impl<T> FillValue<Option<T>> for T
where T: Send + 'static,

Source§

async fn fill(self) -> Result<Option<T>, Error>

Resolves the column’s value. Read more
Source§

impl<T> FillValue<T> for T
where T: Send + 'static,

Source§

async fn fill(self) -> Result<T, Error>

Resolves the column’s value. Read more
Source§

impl<K> ForeignKey<K> for K

Source§

fn key(&self) -> Option<&K>

Returns the key, or None when the field holds no key.
Source§

fn __from_key(key: K) -> K

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

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

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self> ⓘ

Attaches the current Context to this type, returning a WithContext wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

Source§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
Source§

impl<T, N> NotifiedBy<T> for N
where T: Notification<N>,

Source§

fn __routes(&self) -> Vec<Route>

Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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 = !

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

fn try_from(value: U) -> Result<T, !>

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, V> UpdateValue<T> for V
where V: FillValue<T>,

Source§

fn __update<M, U>(self, column: Column<M, T>, update: U) -> U
where M: Model, U: Updates<M>, T: IntoExpr + Clone + Send + Sync + 'static,

Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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