lua-resty-template icon indicating copy to clipboard operation
lua-resty-template copied to clipboard

can't use blocks before {*view*} in layout

Open xiangnanscu opened this issue 4 years ago • 4 comments

local template = require "resty.template"
local layout = [[
<div>
  {*blocks.title*}
  {*view*}
  {*blocks.title*}
  {*blocks.title*}
</div>]]
    local content = [[
{-title-}
<div>I'm title</div>
{-title-}
<h1>hello!</h1>]]
ngx.say(template.new(content, layout):process())

output:

<div>
  
  <h1>hello!</h1>
  <div>I'm title</div>
  <div>I'm title</div>
</div>

what I expect is:

<div>
  <div>I'm title</div>
  <h1>hello!</h1>
  <div>I'm title</div>
  <div>I'm title</div>
</div>

xiangnanscu avatar Dec 13 '21 08:12 xiangnanscu

@xiangnanscu,

does it work if you change: https://github.com/bungle/lua-resty-template/blob/master/lib/resty/template.lua#L302

                    context.view = function(ctx) return template.process(view, ctx or context) end

to:

                    context.view = template.process(view, context)

I still need to think about the possible consequences of this change. One at least is that you cannot pass ctx to view anymore.

bungle avatar Dec 13 '21 09:12 bungle

Yes, it works but that's a problem. Currently I do this in layout:

local layout = [[
{% local view_content = type(view)=='function' and view() or view %}
<div>
  {*blocks.title*}
  {*view_content*}
  {*blocks.title*}
  {*blocks.title*}
</div>]]

xiangnanscu avatar Dec 13 '21 09:12 xiangnanscu

@bungle Could we handle {*view*} specially at the beginning of template.parse? i.e:

context=... or {}
local ___,blocks,layout={},blocks or {}
local function include(v, c) return template.process(v, c or context) end
local function echo(...) for i=1,select("#", ...) do ___[#___+1] = tostring(select(i, ...)) end end
local view=type(view)=='function' and view() or view

xiangnanscu avatar Dec 13 '21 10:12 xiangnanscu

@xiangnanscu, yes, that sounds like a better option. Let me take a look.

bungle avatar Dec 14 '21 13:12 bungle