Skip to content

Commit

Permalink
Add a search page
Browse files Browse the repository at this point in the history
  • Loading branch information
furo321 committed Apr 15, 2024
1 parent 684452c commit aec97af
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
2 changes: 1 addition & 1 deletion sql/articles/search.sql
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ SELECT
FROM
articles
WHERE
to_tsquery($1) @@ search_vec AND is_published = true
to_tsquery(FORMAT('%s', ARRAY_TO_STRING(STRING_TO_ARRAY($1, ' '), ' & '))) @@ search_vec AND is_published = true
10 changes: 9 additions & 1 deletion src/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,14 @@ async fn about_us(db: &State<DatabaseHandler>) -> Result<Template, Error> {
Ok(Template::render("about", context! { tags }))
}

#[get("/search?<q>")]
async fn search(q: Option<&str>, db: &State<DatabaseHandler>) -> Result<Template, Error> {
let tags = Text::get_all_tags(db, None).await?;
let texts = Text::search(db, q.unwrap_or("")).await?;

Ok(Template::render("search", context! { texts, tags, q }))
}

#[get("/t/<id>/<title_slug>")]
async fn text_by_id(
id: i32,
Expand Down Expand Up @@ -53,5 +61,5 @@ async fn feed_atom(db: &State<DatabaseHandler>) -> Result<Template, Error> {

/// This should be mounted on `/`!
pub fn get_all_routes() -> Vec<Route> {
routes![landing, about_us, text_by_id, feed_atom]
routes![landing, about_us, search, text_by_id, feed_atom]
}
25 changes: 25 additions & 0 deletions templates/search.html.tera
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{% extends "templates/app" %}

{% block main %}
<h1>Sök</h1>
<div>
<form action="/search" method="get">
<input type="text" placeholder="Ange sökord" name="q" id="q" value="{% if q %}{{ q }}{% endif %}" required autofocus>
<button type="submit" icon="search" class="btn">Sök</button>
</form>

{% if q %}
{% for text in texts %}
<a href="/t/{{ text.id }}/{{ text.title_slug }}" class="news-item">
<img src="https://source.unsplash.com/random/600x200?{{ text.id }}" alt="Random image" loading="lazy">
<h1>{{ text.title }}</h1>
<p><span class="type">{{ text.text_type }}</span>{{ text.lead_paragraph }}</p>
<p class="news-meta-data">{{ text.author }}, {{ text.created_at | date(format="%R") }}</p>
</a>
{% endfor %}
{% if texts | length == 0 %}
<p>Hittade ingenting! 😢</p>
{% endif %}
{% endif %}
</div>
{% endblock main %}

0 comments on commit aec97af

Please sign in to comment.