Expand description
Processor for RFC 6570 URI Template.
§Usage
- Prepare a template.
- You can create a template as
UriTemplateStr
type (borrowed) orUriTemplateString
type (owned).
- You can create a template as
- 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;
use iri_string::template::context::{Context, VarName, 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}")?;
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)
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;
pub use self::context::DynamicContext;
Modules§
- Template expansion context.
- simple_
context alloc
Simple general-purpose context type.
Structs§
- Creation
Error alloc
Error on conversion into a URI template type. - Template construction and expansion error.
- Template expansion result.
- A borrowed slice of a URI template.
- UriTemplate
String alloc
An owned slice of a URI template. - An iterator of variables in a URI template.
Type Aliases§
- VarName
Deprecated Deprecated old name oftemplate::context::VarName
.