Module iri_string::template
source · [−]Expand description
Processor for RFC 6570 URI Template.
Usage
- Prepare a template.
- Template type is
UriTemplateStr
(borrowed) andUriTemplateString
(owned).
- Template type is
- Prepare a context.
- Create a value of type that implements
Context
trait. - Or, if you use
SimpleContext
, insert key-value pairs into it.
- Create a value of type that implements
- Expand.
- Pass the context to
UriTemplateStr::expand
method of the template.
- Pass the context to
- Use the result.
Examples
Custom context type
For details, see the documentation of context
module.
use core::fmt;
use iri_string::spec::{IriSpec, Spec, UriSpec};
use iri_string::template::{UriTemplateStr, VarName};
use iri_string::template::context::{Context, Visitor};
struct UserInfo {
username: &'static str,
utf8_available: bool,
}
impl Context for UserInfo {
fn visit<V: Visitor>(
&self,
visitor: V,
) -> V::Result {
match visitor.var_name().as_str() {
"username" => visitor.visit_string(self.username),
"utf8" => {
if self.utf8_available {
// U+2713 CHECK MARK
visitor.visit_string("\u{2713}")
} else {
visitor.visit_undefined()
}
}
_ => visitor.visit_undefined()
}
}
}
let context = UserInfo {
username: "foo",
utf8_available: true,
};
let template = UriTemplateStr::new("/users/{username}{?utf8}")?;
#[cfg(feature = "alloc")] {
assert_eq!(
template.expand::<UriSpec, _>(&context)?.to_string(),
"/users/foo?utf8=%E2%9C%93"
);
assert_eq!(
template.expand::<IriSpec, _>(&context)?.to_string(),
"/users/foo?utf8=\u{2713}"
);
SimpleContext
type (enabled by alloc
feature flag)
#[cfg(feature = "alloc")] {
use iri_string::spec::{IriSpec, UriSpec};
use iri_string::template::UriTemplateStr;
use iri_string::template::simple_context::SimpleContext;
let mut context = SimpleContext::new();
context.insert("username", "foo");
// U+2713 CHECK MARK
context.insert("utf8", "\u{2713}");
let template = UriTemplateStr::new("/users/{username}{?utf8}")?;
assert_eq!(
template.expand::<UriSpec, _>(&context)?.to_string(),
"/users/foo?utf8=%E2%9C%93"
);
assert_eq!(
template.expand::<IriSpec, _>(&context)?.to_string(),
"/users/foo?utf8=\u{2713}"
);
Re-exports
pub use self::context::Context;
Modules
Template expansion context.
simple_context
alloc
Simple general-purpose context type.
Structs
CreationError
alloc
Error on conversion into a URI template type.
Template construction and expansion error.
Template expansion result.
UriTemplateStr
alloc
A borrowed slice of a URI template.
UriTemplateString
alloc
An owned slice of a URI template.
Variable name.