carpentries / varnish

Template for pkgdown site
https://carpentries.github.io/varnish/
Other
7 stars 25 forks source link

Catalog bare words in templates that should be used for translation #104

Closed zkamvar closed 9 months ago

zkamvar commented 9 months ago

to support https://github.com/carpentries/sandpaper/pull/546, {varnish} needs to be able to support translations. One of the ways we do this is via the $translate field in the pkgdown data.

based on https://github.com/carpentries/sandpaper/issues/205#issuecomment-1351663885, hard-coded English text needs to be replaced with mustache templating:

For example, this link to key points from the header has "Key Points" hard-coded:

<a class="nav-link" href="{{#site}}{{root}}{{/site}}key-points.html">
Key Points
</a>

To use translations, we should do the following:

  1. in {sandpaper} add a function that will add $translate field to the {pkgdown} object in build_site() that will include a translation for keypoints:
    add_varnish_translations <- function(pkg) {
     pkg$translate <- list(
       keypoints = tr_("Key Points")
     )
     return(pkg)
    }
  2. in {varnish}, use the mustache template to replace the hard-coded text:
    <a class="nav-link" href="{{#site}}{{root}}{{/site}}key-points.html">
    {{#translate}}{{keypoints}}{{/translate}}
    </a>

Once we come up with a catalog, then we can pass that to {sandpaper} and have the translations available.

zkamvar commented 9 months ago

This has been implemented in https://github.com/carpentries/sandpaper/pull/546#issuecomment-1828304909, but it's a bit incomplete because we need to consider phrases that include variables so that more rich translations can be implemented.

Here is the code to extract the text to be translated:

get_bare_text <- function(path) {
  html <- xml2::read_html(path)
  no_brace <- "not(starts-with(normalize-space(text()), '{'))"
  no_blank <- "not(normalize-space(text())='')"
  no_mathjax <- "not(starts-with(normalize-space(text()), 'MathJax.Hub'))"
  no_docsearch <- "not(starts-with(normalize-space(text()), 'docsearch'))"

  xpath <- sprintf(".//*[%s and %s and %s and %s]", 
    no_brace, no_blank, no_mathjax, no_docsearch)
  nodes <- xml2::xml_find_all(html, xpath)
  unique(trimws(xml2::xml_text(nodes)))
}

get_varnish_text <- function() {
  templates <- system.file("pkgdown", "templates", package = "varnish")
  res <- lapply(list.files(templates, pattern = "*html", full.names = TRUE),
    get_bare_text)
  reslist <- unique(unlist(res, use.names = FALSE))
  resvar <- abbreviate(reslist, 6)
  clipr::write_clip(paste0(resvar, " = _tr(", sQuote(reslist, q = 2), "),"))
}