diff --git a/src/main.rs b/src/main.rs index fa9ac0b..3cc03df 100644 --- a/src/main.rs +++ b/src/main.rs @@ -24,6 +24,7 @@ use std::vec::Vec; use tera::Context; const TITLES: [&str; 4] = ["/* {} */", "# {}", "// {}", ""]; +const MAX_POSTS_PER_PAGE: i64 = 20; fn establish_connection() -> PgConnection { dotenv().ok(); @@ -32,21 +33,29 @@ fn establish_connection() -> PgConnection { PgConnection::establish(&database_url).expect(&format!("Error connecting to {}", database_url)) } -pub fn get_posts() -> Vec { +fn get_posts(page: i64) -> (Vec, i64) { use schema::posts::dsl::*; let connection = establish_connection(); - posts + let visible_posts = posts .filter(published.eq(true)) - .limit(20) + .limit(MAX_POSTS_PER_PAGE) + .offset(MAX_POSTS_PER_PAGE * (page - 1)) .load::(&connection) - .expect("Error loading posts") + .expect("Error loading posts"); + + let number_of_posts: i64 = posts + .filter(published.eq(true)) + .count() + .get_result(&connection) + .expect("Error counting the posts"); + + (visible_posts, number_of_posts) } #[get("/?")] fn index(page: Option) -> Template { - let page = page.unwrap_or_else(|| 0); - println!("{}", page); + let page = page.unwrap_or_else(|| 1); let mut context = Context::new(); @@ -54,8 +63,14 @@ fn index(page: Option) -> Template { let title_fmt = TITLES[rng.gen_range(0, TITLES.len())]; let title = str::replace(title_fmt, "{}", "CódigoComentado"); + let (posts, n_posts) = get_posts(page as i64); + + let total_pages = (n_posts as f64 / MAX_POSTS_PER_PAGE as f64).ceil() as i64; + context.insert("title", &title); - context.insert("posts", &get_posts()); + context.insert("posts", &posts); + context.insert("total_pages", &total_pages); + context.insert("actual_page", &page); Template::render("index", context) } diff --git a/static/css/index.css b/static/css/index.css index 14c5a16..42d7482 100644 --- a/static/css/index.css +++ b/static/css/index.css @@ -45,7 +45,14 @@ article figure img { grid-area: info; } -article strong { +strong { font-family: monospace; font-size: 10px; } + +div.pagination { + margin-top: 50px; + width: auto; + height: 3em; + text-align: center; +} diff --git a/templates/index.html.tera b/templates/index.html.tera index af93c66..83e92ef 100644 --- a/templates/index.html.tera +++ b/templates/index.html.tera @@ -20,4 +20,14 @@ {% endfor %} + + {# Pages #} + {% endblock content %}