Struct Context

Source
pub struct Context {
    pub path: PathBuf,
    pub dir_path: PathBuf,
    pub root_path: PathBuf,
    /* private fields */
}
Expand description

Tiny wrapper around “Tera context” with some additional information.

Fields§

§path: PathBuf

First positional command line argument.

§dir_path: PathBuf

The directory (only) path corresponding to the first positional command line argument. The is our working directory and the directory where the note file is (will be) located.

§root_path: PathBuf

dir_path is a subdirectory of root_path. root_path is the first directory, that upwards from dir_path, contains a file named FILENAME_ROOT_PATH_MARKER (or, / if not marker file can be found). The root directory is interpreted by Tp-Note’s viewer as its base directory: only files within this directory are served.

Implementations§

Source§

impl Context

A thin wrapper around tera::Context storing some additional information.

Source

pub fn from(path: &Path) -> Self

Constructor: path is the first positional command line parameter <path> (see man page). path must point to a directory or a file.

A copy of path is stored in self.ct as key TMPL_VAR_PATH. It directory path as key TMPL_VAR_DIR_PATH.

use std::path::Path;
use tpnote_lib::settings::set_test_default_settings;
use tpnote_lib::config::TMPL_VAR_DIR_PATH;
use tpnote_lib::config::TMPL_VAR_PATH;
use tpnote_lib::context::Context;
set_test_default_settings().unwrap();

let mut context = Context::from(&Path::new("/path/to/mynote.md"));

assert_eq!(context.path, Path::new("/path/to/mynote.md"));
assert_eq!(context.dir_path, Path::new("/path/to/"));
assert_eq!(&context.get(TMPL_VAR_PATH).unwrap().to_string(),
            r#""/path/to/mynote.md""#);
assert_eq!(&context.get(TMPL_VAR_DIR_PATH).unwrap().to_string(),
            r#""/path/to""#);
Source

pub fn insert_content( &mut self, tmpl_var: &str, tmpl_var_header: &str, input: &impl Content, ) -> Result<(), NoteError>

Inserts clipboard or stdin data into the context. The data may contain some copied text with or without a YAML header. The latter usually carries front matter variable. These are added separately via insert_front_matter(). The input data below is registered with the key name given by tmpl_var. Typical names are "clipboard" or "stdin". If the below input contains a valid YAML header, it will be registered in the context with the key name given by tmpl_var_header. This string is typically one of clipboard_header or std_header. The raw data that will be inserted into the context.

use std::path::Path;
use tpnote_lib::settings::set_test_default_settings;
use tpnote_lib::context::Context;
use tpnote_lib::content::Content;
use tpnote_lib::content::ContentString;
set_test_default_settings().unwrap();

let mut context = Context::from(&Path::new("/path/to/mynote.md"));

context.insert_content("clipboard", "clipboard_header",
     &ContentString::from(String::from("Data from clipboard.")));
assert_eq!(&context.get("clipboard").unwrap().to_string(),
    "\"Data from clipboard.\"");

context.insert_content("stdin", "stdin_header",
     &ContentString::from("---\ntitle: \"My Stdin.\"\n---\nbody".to_string()));
assert_eq!(&context.get("stdin").unwrap().to_string(),
    r#""body""#);
assert_eq!(&context.get("stdin_header").unwrap().to_string(),
    r#""title: \"My Stdin.\"""#);
// "fm_title" is dynamically generated from the header variable "title".
assert_eq!(&context
           .get("fm").unwrap()
           .get("fm_title").unwrap().to_string(),
    r#""My Stdin.""#);

Methods from Deref<Target = Context>§

Source

pub fn insert<T, S>(&mut self, key: S, val: &T)
where T: Serialize + ?Sized, S: Into<String>,

Converts the val parameter to Value and insert it into the context.

Panics if the serialization fails.

let mut context = tera::Context::new();
context.insert("number_users", &42);
Source

pub fn try_insert<T, S>(&mut self, key: S, val: &T) -> Result<(), Error>
where T: Serialize + ?Sized, S: Into<String>,

Converts the val parameter to Value and insert it into the context.

Returns an error if the serialization fails.

let mut context = Context::new();
// user is an instance of a struct implementing `Serialize`
if let Err(_) = context.try_insert("number_users", &user) {
    // Serialization failed
}
Source

pub fn extend(&mut self, source: Context)

Appends the data of the source parameter to self, overwriting existing keys. The source context will be dropped.

let mut target = Context::new();
target.insert("a", &1);
target.insert("b", &2);
let mut source = Context::new();
source.insert("b", &3);
source.insert("d", &4);
target.extend(source);
Source

pub fn get(&self, index: &str) -> Option<&Value>

Returns the value at a given key index.

Source

pub fn remove(&mut self, index: &str) -> Option<Value>

Remove a key from the context, returning the value at the key if the key was previously inserted into the context.

Source

pub fn contains_key(&self, index: &str) -> bool

Checks if a value exists at a specific index.

Trait Implementations§

Source§

impl Clone for Context

Source§

fn clone(&self) -> Context

Returns a copy 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 Debug for Context

Source§

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

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

impl Deref for Context

Auto-dereference for convenient access to tera::Context.

Source§

type Target = Context

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl DerefMut for Context

Auto-dereference for convenient access to tera::Context.

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
Source§

impl PartialEq for Context

Source§

fn eq(&self, other: &Context) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for Context

Auto Trait Implementations§

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, 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<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T