Module:TruncDesc: Difference between revisions

From TwogPedia
No edit summary
No edit summary
Tag: Manual revert
 
(2 intermediate revisions by the same user not shown)
Line 9: Line 9:
     text = mw.text.trim(text)
     text = mw.text.trim(text)


     local max = 155
     local max = 160
     if mw.ustring.len(text) <= max then
     if mw.ustring.len(text) <= max then
         return text
         return text
Line 15: Line 15:


     local truncated = mw.ustring.sub(text, 1, max)
     local truncated = mw.ustring.sub(text, 1, max)
     local lastDot = mw.ustring.find(truncated, "[%.%?!][%s]") or mw.ustring.find(truncated, "[%.%?!]$")
 
     if lastDot then
     local lastPunct = mw.ustring.find(truncated, "[%.%?!][%s]") or mw.ustring.find(truncated, "[%.%?!]$")
         truncated = mw.ustring.sub(truncated, 1, lastDot)
     if lastPunct then
         truncated = mw.ustring.sub(truncated, 1, lastPunct)
     else
     else
         local lastSpace = mw.ustring.find(truncated, " ", -1, true)
         local lastSpace = mw.ustring.find(truncated, " ", -1, true)
Line 25: Line 26:
     end
     end


     return mw.text.trim(truncated) .. (mw.ustring.len(text) > max and "..." or "")
     truncated = mw.text.trim(truncated)
 
    local endsWithPunct = mw.ustring.find(truncated, "[%.%?!]$")
    if mw.ustring.len(text) > max and not endsWithPunct then
        truncated = truncated .. "..."
    end
 
    return truncated
end
end


return p
return p

Latest revision as of 09:26, 15 January 2026

Documentation for this module may be created at Module:TruncDesc/doc

local p = {}

function p.generate(frame)
    local manual = frame.args.seo_description or ""
    local content = frame.args.content or ""
    local text = (manual ~= "") and manual or content

    text = mw.ustring.gsub(text, "%s+", " ")
    text = mw.text.trim(text)

    local max = 160
    if mw.ustring.len(text) <= max then
        return text
    end

    local truncated = mw.ustring.sub(text, 1, max)

    local lastPunct = mw.ustring.find(truncated, "[%.%?!][%s]") or mw.ustring.find(truncated, "[%.%?!]$")
    if lastPunct then
        truncated = mw.ustring.sub(truncated, 1, lastPunct)
    else
        local lastSpace = mw.ustring.find(truncated, " ", -1, true)
        if lastSpace then
            truncated = mw.ustring.sub(truncated, 1, lastSpace - 1)
        end
    end

    truncated = mw.text.trim(truncated)

    local endsWithPunct = mw.ustring.find(truncated, "[%.%?!]$")
    if mw.ustring.len(text) > max and not endsWithPunct then
        truncated = truncated .. "..."
    end

    return truncated
end

return p