Skip to content

Speed Up HTML Rendering Using raw_html #739

@PingoLee

Description

@PingoLee

Hi, I was wondering if we could add this function to 'src/renderers/Html.jl'. It would make static page rendering faster.

function raw_html(viewfile::Genie.Renderer.FilePath;
          layout::Union{Nothing,Genie.Renderer.FilePath,String} = nothing,
          cache::Union{Nothing,String} = nothing,
          status::Int = 200,
          headers::Genie.Renderer.HTTPHeaders = Genie.Renderer.HTTPHeaders(),
          vars...) :: Genie.Renderer.HTTP.Response
  
  Genie.Renderer.WebRenderable(Genie.Renderer.render(MIME"text/html", viewfile, cache; layout, vars...), status, headers) |> Genie.Renderer.respond
end

"""Render a raw HTML string with HTML escaping for variables"""
function Genie.Renderer.render(::Type{MIME"text/html"}, viewfile::Genie.Renderer.FilePath, cache::Union{Nothing,String};
                                layout::Union{String,Nothing,Genie.Renderer.FilePath} = nothing, vars...)::Genie.Renderer.WebRenderable
  try
    sview = read(viewfile, String)
    if layout !== nothing
      slayout::String = if isa(layout, Genie.Renderer.FilePath)
        read(layout, String)
      else
        layout
      end
      sview = replace(slayout,  r"<%\s*@yield\s*%>" => sview)
    end
    
    for (k, v) in vars
      pattern = "<%\\s*" * escape_string(k |> string) * "\\s*%>"  # Construct the pattern string with k interpolated
      regex = Regex(pattern)  # Convert the pattern string into a Regex object
      sview = replace(sview, regex => v)  # Use the regex in the replace function
    end

    # remove other <% %> tags
    sview = replace(sview, r"<%\s*.*\s*%>" => "")
    
    Genie.Renderer.WebRenderable(sview)
  catch ex
    isa(ex, KeyError) && Genie.Renderer.changebuilds() # it's a view error so don't reuse them
    rethrow(ex)
  end
end

Example to use:

route("/") do
  Genie.Renderer.Html.raw_html(Genie.Renderer.filepath("layouts\\templates\\linkage.jl.html"), layout = Genie.Renderer.filepath("layouts\\app.jl.html"), scripts="<script src='/js/cust/linksus.js'></script>")
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions