templating

This commit is contained in:
Xsivax 2021-09-19 21:50:40 +02:00
parent 93f3ab7fa3
commit abf475e516
14 changed files with 157 additions and 165 deletions

View file

@ -7,15 +7,14 @@ edition = "2018"
[dependencies.rocket]
version = "0.5.0-rc.1"
features = ["json"]
default-features = false
[dependencies]
serde = "1.0.130"
serde_json = "1.0.67"
lazy_static = "1.4.0"
askama_rocket = "0.10.0"
[dependencies.rocket_dyn_templates]
version = "0.1.0-rc.1"
features = ["tera"]
#diesel = { version = "1.4.4", features = ["mysql"]}
#dotenv = "0.15.0"
features = ["tera"]

View file

@ -1,6 +1,5 @@
start dev server: make run_dev
start docker container: docker-compose up
[To do for me ]
@ -19,9 +18,9 @@ Frontend:
! Fix css queries
! Fix css footer
! Fix css home posts-section
! Fix js open menu
! add css Animations
! cleaner look
! Add 3d canvas, images
! webp images
! Fix js open menu
! improve js code, use TS ?

View file

@ -1,11 +1,13 @@
{
"lang" : {
"json" : "object",
"test" : ["a", "b", "c"],
"title" : "JSON"
"en" : "English",
"fr" : "Francais",
"it" : "Italiano"
},
"title": {
"en": "Hello Json"
"content": {
"en": "Hello Json",
"it" : "Ciao Json"
}
}

View file

@ -1,12 +1,11 @@
use std::fs::{ File };
use rocket_dyn_templates::tera::Value;
use rocket_dyn_templates::tera::Map;
use rocket_dyn_templates::tera::Context;
use rocket_dyn_templates::tera::Error;
use serde::{ Serialize };
use serde::Serialize;
use std::io::BufReader;
use serde_json::Value;
// Define File for language handling
pub const LANG_FILE : &str ="./lang.json";
@ -15,59 +14,89 @@ pub const LANG_FILE : &str ="./lang.json";
lazy_static! {
#[derive(Serialize, Debug)]
pub static ref LANG : Result<Context, Error> = init_lang();
pub static ref LANG : Value = init_lang();
}
fn init_lang() -> Value {
let file = File::open(LANG_FILE).expect("can not open file");
// read file into buffer
let reader = BufReader::new(file);
let data : Value = serde_json::from_reader(reader).expect("can not parse Json contents");
data
}
// Convert Map to Context
pub fn init_lang() -> Result<Context, Error> {
let map = &json_to_map();
let context : Result<Context, Error> = Context::from_value(Value::Object(map.clone().unwrap()));
// pub fn init_lang() -> Result<Context, Error> {
// let map = &json_to_map();
// let context : Result<Context, Error> = Context::from_value(Value::Object(map.clone().unwrap()));
match context {
Ok(context) => Ok(context) ,
Err(error) => Err(Error::msg(error)),
}
}
// match context {
// Ok(context) => {
// Ok(context)
// },
// Err(error) => Err(Error::msg(error)),
// }
// }
// // Convert JSON from file to Map<String, Value> structure
// pub fn json_to_map()-> Option<Map<String, Value>> {
// // Open lang.json
// let file = File::open(LANG_FILE).expect("can not open file");
// // read file into buffer
// let reader = BufReader::new(file);
// // read JSON into Value
// let json : Value = serde_json::from_reader(reader).expect("can not read Json contents");
// // store JSON key/value pairs in Map
// let obj: Map<String, Value> = json.as_object().unwrap().clone();
// // return struct Map
// Some(obj)
// }
// Convert JSON from file to Map<String, Value> structure
fn json_to_map()-> Option<Map<String, Value>> {
let file = File::open(LANG_FILE).expect("unable to open file");
let json : Value = serde_json::from_reader(file).expect("file should be JSON syntax");
let value = json["lang"].as_object();
match value {
None => None,
Some(value) => Some(value.clone()),
}
}
pub fn all_to_map() -> Option<Map<String, Value>> {
let file = File::open(LANG_FILE).expect("unable to open file");
let json : Value = serde_json::from_reader(file).expect("file should be JSON syntax");
let object = json.as_object();
// fn return_value( key: &str, value: &str ) -> Option<String>{
// let data = json_to_map().unwrap();
match object {
None => None,
Some(object) => Some(object.clone()),
}
}
// let value = data.get(key).unwrap().get(value).unwrap();
pub fn debug() {
let map = &all_to_map();
// Some(value.to_string())
println!("{:#?}", map );
}
// }
pub fn get_key() {
// pub fn debug() {
// println!("context is {:#?}", init_lang());
// }
let map = &all_to_map().unwrap();
let keys = map.keys();
for key in keys {
println!("{:?}", key );
}
}
// pub fn print_key( key : &str) {
// let data = json_to_map().unwrap();
// let mut keys = data.keys();
// let my_key = keys.find(|&x| x == key ).unwrap();
// let result = data.get(my_key).unwrap();
// println!("requested value is {:?}", result );
// }

View file

@ -4,10 +4,9 @@ use rocket::fs::NamedFile;
// Error type 404
use rocket::response::status::NotFound;
// Responder type Template
use rocket_dyn_templates::{ Template };
use crate::build_rocket::{ templates };
use crate::build_rocket::{ templates, config };
use rocket_dyn_templates::Template;
// Configure requests
// generate routes, set attributes
@ -15,10 +14,10 @@ use crate::build_rocket::{ templates, config };
// set uri
#[get("/")]
// if success call handler
pub async fn index() -> Result<NamedFile, NotFound<String>> {
NamedFile::open("templates/index.html").await.map_err(|e|NotFound(e.to_string()))
}
pub fn index() -> Template {
let context = templates::TplIndex::new();
Template::render("index", &context)
}
// serve other pages (html GET)
// create routes for pages
@ -133,18 +132,9 @@ use crate::build_rocket::{ templates, config };
}
#[get("/privacy")]
pub async fn privacy() -> Result<NamedFile, NotFound<String>> {
NamedFile::open("templates/privacy-policy.html").await.map_err(|e|NotFound(e.to_string()))
}
pub fn privacy() -> Template {
let context = templates::TplPrivacy::new();
Template::render("privacy-policy", &context)
}
#[get("/test")]
// Render Template Responder
pub fn test() -> Template {
config::debug();
// that's the one
config::get_key();
Template::render("test_extend", &config::LANG )
}

View file

@ -1,35 +1,32 @@
use rocket_dyn_templates::tera::Context;
use rocket::serde::Serialize;
// Serde Data Model conversion
use rocket::serde::{ Serialize };
use crate::build_rocket::{ config };
// Implement serde Serialize to create context
// context Template index
#[derive(Serialize)]
pub struct Tpl {
pub lang : String,
pub struct TplIndex {
pub title: String,
}
pub fn print_value() {
let lang : &Context = &config::init_lang().unwrap();
let value = lang.get("json").unwrap();
println!("Value = {:#?}", value);
impl TplIndex {
pub fn new() -> TplIndex {
TplIndex {
title: String::from("Cannabinieri CBD"),
}
}
}
pub fn print_object() {
let object = &config::init_lang().unwrap();
println!("Context = {:#?}", object);
// context privacy-policy
#[derive(Serialize)]
pub struct TplPrivacy {
// replace this with values from json file
pub title : String,
}
impl TplPrivacy {
pub fn new() -> TplPrivacy {
TplPrivacy {
title : String::from("Privacy Policy"),
}
}
}

View file

@ -7,7 +7,6 @@ extern crate lazy_static;
mod build_rocket;
use crate::build_rocket::{ get, get_static_files };
// support for template as Responder
use rocket_dyn_templates::Template;
// Equivalent to main()
@ -39,14 +38,12 @@ async fn main() -> Result<(), rocket::Error> {
routes! [ get::spiderpi, get::join ])
.mount("/learn",
routes! [ get::about, get::partners, get::meet, get::blog, get::code ])
.mount("/policies",
routes! [ get::policies_info, get::privacy ])
// test route template
.mount("/",
routes! [ get::test] )
// initialize and maintain templating state
.attach(Template::fairing())
// Add Tera Templating support
.attach(Template::fairing())
.ignite().await?

View file

@ -73,7 +73,7 @@
.top-bar {
background-color:white;
grid-area: top-bar;
display: flex;
display: flex !important;
align-items: center;
}
@ -1472,7 +1472,7 @@
/* Adjust Media Queries ! */
@media (max-width: 768px) {
body {
background-color: white;
@ -2950,7 +2950,6 @@
.desktop {
display: none;
}
}

View file

@ -1,13 +1,15 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>{{ lang.title }}</title>
</head>
<body>
{%include "test_include" %}
<h1>{{ title }}</h1>
<div id ="content">{% block content %}Me too {% endblock content %}
</div>
</body>
<html lang="en">
<head>
{% block head %}
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type=image/svg+xml href="../img/Logo.svg">
<title>{% block title %}Base{% endblock title %} </title>
{% endblock head %}
</head>
<body>
{% block content %}{% endblock content %}
</body>
</html>

View file

@ -1,25 +1,19 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-eqiv="X-UA-Compatible" content="ie=edge"/>
<link rel="stylesheet" type="text/css" href="css/index.css">
<link rel="stylesheet" type="text/css" href="css/nav.css">
<link rel="icon" type="image/webp" href="img/Logo.svg">
<title>
Cannabinieri CBD
</title>
<!--Figure out how to load fontawesome icons-->
{%extends "base"%}
{%block head%}
{{super()}}
<link rel="stylesheet" type="text/css" href="css/index.css">
<link rel="stylesheet" type="text/css" href="css/nav.css">
<script type="text/javascript" defer src="fontawesome/all.js"></script>
<script type="text/javascript" src="jquery/jquery-3.5.1.min.js"></script>
</head>
<body>
{%block title%} {{title}} {%endblock title%}
{%endblock head%}
{%block content%}
{{super()}}
<div class="wrapper">
<nav class="top-bar">
<!--Add Askama Language Handling-->
<div class="languages">
<a href="static/languages/deutsch.html">{{ name }}</a>
<a href="static/languages/deutsch.html">Deutsch</a>
<a href="static/languages/italiano.html">Italiano |</a>
<a href="static/languages/francais.html">Francais </a>
</div>
@ -451,5 +445,4 @@
<script src="js/main.js" type="application/javascript"></script>
<script src="js/pages.js" type="application/javascript"></script>
<script src="js/slider.js" type="application/javascript"></script>
</body>
</html>
{% endblock content %}

View file

@ -1,15 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type= "text/css" href="../../css/footer-pages/privacy.css">
<title>Privacy Policy</title>
</head>
<body>
<h1>Privacy Policy</h1>
<p>Add info how data is handled and licence of code</p>
<h1>{{ name }}</h1>
</body>
</html>

View file

@ -0,0 +1,10 @@
{%extends "base"%}
{%block title%}{{title}}{%endblock title%}
{%block head%}
{{super()}}
{%endblock head%}
{%block content%}
<h1>Privacy Policy</h1>
<p>Add info how data is handled and licence of code</p>
{%endblock content%}

View file

@ -1,9 +0,0 @@
{%extends "base" %}
{% block content %}
<h1>Override !!</h1>
{{super()}}
{% endblock %}

View file

@ -1 +0,0 @@
<h1>Included a nav {{ contents }}</h1>