Browse Source

templating

master
Xsivax 3 years ago
parent
commit
abf475e516
14 changed files with 158 additions and 166 deletions
  1. +3
    -4
      Cargo.toml
  2. +1
    -2
      README.md
  3. +7
    -5
      lang.json
  4. +74
    -45
      src/build_rocket/config.rs
  5. +11
    -21
      src/build_rocket/get.rs
  6. +22
    -25
      src/build_rocket/templates.rs
  7. +3
    -6
      src/main.rs
  8. +2
    -3
      templates/assets/css/index.css
  9. +13
    -11
      templates/base.html.tera
  10. +12
    -19
      templates/index.html.tera
  11. +0
    -15
      templates/privacy-policy.html
  12. +10
    -0
      templates/privacy-policy.html.tera
  13. +0
    -9
      templates/test_extend.html.tera
  14. +0
    -1
      templates/test_include.html.tera

+ 3
- 4
Cargo.toml View File

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

+ 1
- 2
README.md View File

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

+ 7
- 5
lang.json View File

@ -1,11 +1,13 @@
{ {
"lang" : { "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"
} }
} }

+ 74
- 45
src/build_rocket/config.rs View File

@ -1,12 +1,11 @@
use std::fs::{ File }; 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 // Define File for language handling
pub const LANG_FILE : &str ="./lang.json"; pub const LANG_FILE : &str ="./lang.json";
@ -15,59 +14,89 @@ pub const LANG_FILE : &str ="./lang.json";
lazy_static! { lazy_static! {
#[derive(Serialize, Debug)] #[derive(Serialize, Debug)]
pub static ref LANG : Result<Context, Error> = init_lang();
pub static ref LANG : Value = init_lang();
} }
// 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()));
match context {
Ok(context) => Ok(context) ,
Err(error) => Err(Error::msg(error)),
}
}
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");
// 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()),
}
data
} }
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();
match object {
None => None,
Some(object) => Some(object.clone()),
}
}
pub fn debug() {
let map = &all_to_map();
// 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()));
println!("{:#?}", map );
}
// match context {
// Ok(context) => {
// Ok(context)
// },
// Err(error) => Err(Error::msg(error)),
// }
// }
pub fn get_key() {
// // 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);
let map = &all_to_map().unwrap();
// // read JSON into Value
// let json : Value = serde_json::from_reader(reader).expect("can not read Json contents");
let keys = map.keys();
// // store JSON key/value pairs in Map
// let obj: Map<String, Value> = json.as_object().unwrap().clone();
for key in keys {
// // return struct Map
// Some(obj)
// }
println!("{:?}", key );
}
}
// fn return_value( key: &str, value: &str ) -> Option<String>{
// let data = json_to_map().unwrap();
// let value = data.get(key).unwrap().get(value).unwrap();
// Some(value.to_string())
// }
// pub fn debug() {
// println!("context is {:#?}", init_lang());
// }
// 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 );
// }

+ 11
- 21
src/build_rocket/get.rs View File

@ -4,10 +4,9 @@ use rocket::fs::NamedFile;
// Error type 404 // Error type 404
use rocket::response::status::NotFound; 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 // Configure requests
// generate routes, set attributes // generate routes, set attributes
@ -15,10 +14,10 @@ use crate::build_rocket::{ templates, config };
// set uri // set uri
#[get("/")] #[get("/")]
// if success call handler // 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) // serve other pages (html GET)
// create routes for pages // create routes for pages
@ -133,18 +132,9 @@ use crate::build_rocket::{ templates, config };
} }
#[get("/privacy")] #[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 )
}

+ 22
- 25
src/build_rocket/templates.rs 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)] #[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"),
}
}
}

+ 3
- 6
src/main.rs View File

@ -7,7 +7,6 @@ extern crate lazy_static;
mod build_rocket; mod build_rocket;
use crate::build_rocket::{ get, get_static_files }; use crate::build_rocket::{ get, get_static_files };
// support for template as Responder
use rocket_dyn_templates::Template; use rocket_dyn_templates::Template;
// Equivalent to main() // Equivalent to main()
@ -39,14 +38,12 @@ async fn main() -> Result<(), rocket::Error> {
routes! [ get::spiderpi, get::join ]) routes! [ get::spiderpi, get::join ])
.mount("/learn", .mount("/learn",
routes! [ get::about, get::partners, get::meet, get::blog, get::code ]) routes! [ get::about, get::partners, get::meet, get::blog, get::code ])
.mount("/policies", .mount("/policies",
routes! [ get::policies_info, get::privacy ]) 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? .ignite().await?

+ 2
- 3
templates/assets/css/index.css View File

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

+ 13
- 11
templates/base.html.tera View File

@ -1,13 +1,15 @@
<!DOCTYPE html> <!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> </html>

templates/index.html → templates/index.html.tera 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" defer src="fontawesome/all.js"></script>
<script type="text/javascript" src="jquery/jquery-3.5.1.min.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"> <div class="wrapper">
<nav class="top-bar"> <nav class="top-bar">
<!--Add Askama Language Handling-->
<div class="languages"> <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/italiano.html">Italiano |</a>
<a href="static/languages/francais.html">Francais </a> <a href="static/languages/francais.html">Francais </a>
</div> </div>
@ -451,5 +445,4 @@
<script src="js/main.js" type="application/javascript"></script> <script src="js/main.js" type="application/javascript"></script>
<script src="js/pages.js" type="application/javascript"></script> <script src="js/pages.js" type="application/javascript"></script>
<script src="js/slider.js" type="application/javascript"></script> <script src="js/slider.js" type="application/javascript"></script>
</body>
</html>
{% endblock content %}

+ 0
- 15
templates/privacy-policy.html 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>

+ 10
- 0
templates/privacy-policy.html.tera 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%}

+ 0
- 9
templates/test_extend.html.tera View File

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

+ 0
- 1
templates/test_include.html.tera View File

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

Loading…
Cancel
Save