Rocket: Is there any way to interact with javascript code?

Created on 10 Jan 2017  路  4Comments  路  Source: SergioBenitez/Rocket

For example, I need to draw some chart on canvas, however, most of graph libraries are write in javascript, so is there any way to do that?

question

Most helpful comment

@lucklove You could also render simple svg charts on the server with e.g. maud:

#[get("/my/chart")]
fn my_chart() -> PreEscaped<String> {
  html!{
    svg width = "200" height = "100" {
       g class = "bar-chart" transform = "translate(10,10)" {
         g class = "bar" {
           rect width="40" height="19" /
           text x = "45" y = "9.5" dy = ".35em" { "4 apples" }
         }
         g class = "bar" {
           rect width="40" height="19" /
           text x = "45" y = "9.5" dy = ".35em" { "4 bananas" }
         }
       }
    }
  }
}

All 4 comments

The typical way to do this is to serve the Javascript file from Rocket via a rendered template. So, you'd have some file, chart.js.tera (or handlebars, whatever suits you better), and then you'd use Template::render("chart", some_context) to inject information from the web application into the javascript file. The guide has more information, as do the API docs.

Alternatively, your Javascript code could perform an AJAX request to your Rocket application to retrieve the data. This is the route to take if the data is dynamic.

@lucklove You could also render simple svg charts on the server with e.g. maud:

#[get("/my/chart")]
fn my_chart() -> PreEscaped<String> {
  html!{
    svg width = "200" height = "100" {
       g class = "bar-chart" transform = "translate(10,10)" {
         g class = "bar" {
           rect width="40" height="19" /
           text x = "45" y = "9.5" dy = ".35em" { "4 apples" }
         }
         g class = "bar" {
           rect width="40" height="19" /
           text x = "45" y = "9.5" dy = ".35em" { "4 bananas" }
         }
       }
    }
  }
}

@SergioBenitez @flosse Get!

Looks like this has been answered. :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

denysvitali picture denysvitali  路  3Comments

marcusball picture marcusball  路  3Comments

incker picture incker  路  3Comments

marceloboeira picture marceloboeira  路  3Comments

Perseus101 picture Perseus101  路  4Comments