FlattenHTML <- function()

in templates/visuals/rhtml/r_files/flatten_HTML.r [18:71]


FlattenHTML <- function(fnameIn, fnameOut)
{
  # Read and parse HTML file
  # Embed all js and css files into one unified file
  
  if(!file.exists(fnameIn))
    return(FALSE)
  
  dir = dirname(fnameIn)
  html = read_html(fnameIn, useInternal = TRUE)
  top = xml_root(html)
  
  # extract all <script> tags with src value
  srcNode=xml_find_all(top, '//script[@src]')
  for (node in srcNode)
  {
    b = xml_attrs(node)
    fname = file.path(dir, b['src'])
    alternateSrc = FindSrcReplacement(fname)
    if (!is.null(alternateSrc))
    {
      s = alternateSrc
      names(s) = 'src'
      newNode = xml_new_root("script")
      xml_set_attrs(newNode, s)
      xml_replace(node, newNode)
    }else{
      str=ReadFileForEmbedding(fname);
      if (!is.null(str))
      {      
        newNode = xml_new_root("script",str)
        xml_set_attrs( newNode, c( type = "text/javascript") )
        xml_replace(node, newNode)
      }
    }
  }
  
  # extract all <link> tags with src value
  linkNode=xml_find_all(top, '//link[@href]')
  for (node in linkNode)
  {
    b = xml_attrs(node)
    fname = file.path(dir, b['href'])
    str = ReadFileForEmbedding(fname, FALSE);
    if (!is.null(str))
    {
      newNode = xml_new_root("style", str)
      xml_replace(node, newNode)
    }
  }
  
  write_xml(html, file = fnameOut)
  return(TRUE)
}