Textpattern CMS support forum

You are not logged in. Register | Login | Help

#1 2019-05-06 08:49:15

jakob
Admin
From: Germany
Registered: 2005-01-20
Posts: 3,547
Website

A neater way of shortening a string without plugins?

Thanks to the new escape attributes and txp:evaluate, we can drop some old tags entirely. While converting the old txp-minimum theme to txp 4.7 (just to try it out) I wanted to replace chh_if_data, etz_striptags, and rss_auto_excerpt with in-built textpattern methods. The first two were straightforward by replacing:

etz_striptags add the attribute escape="tags"
chh_if_data use txp:evaluate

But for rss_auto_excerpt, I needed to find a way of shortening a string. Previously, I’d done that with rvm_substr or smd_wrap but I was trying not to use any plugins.

I cam up with this combination of txp:evaluate and XPath’s substring and string-length (for adding the at the end) functions but it’s not pretty:

<txp:evaluate query='substring("<txp:excerpt escape="tags" />", 1, 158)' escape="trim" /><txp:evaluate query='string-length("<txp:excerpt escape="tags" />" > 158)'>…</txp:evaluate>

(where 158 is the recommended no. of chars in meta_description).

Is there a better way of doing that? If not, might it be possible to add shorten/substr capability to the escape attribute?


TXP Builders – finely-crafted code, design and txp

Offline

#2 2019-05-06 09:57:12

Bloke
Developer
From: Leeds, UK
Registered: 2006-01-29
Posts: 8,775
Website

Re: A neater way of shortening a string without plugins?

While I don’t know of a neater way off the top of my head, we have shied away from substrings and other stuff because of the difficulty in cleanly providing mechanisms to supply the extra parameters.

In smd_wrap for example, the values are embedded (delimited) as part of the transform. While it works, that’s messy and unintuitive at best. In rvm_substr, there’s a dedicated attribute, which is fine for a tag that only does one thing, but if that attribute is dependent on a value in another (when applied to a more general tag or attribute such as escape) it’s less ideal.

So I think the stumbling block is not necessarily adding the ability to do more complex transforms – that’s relatively simple – it’s how to control them. Ideas welcome.


The smd plugin menagerie — for when you need one more gribble of power from Textpattern. Bleeding-edge code available on GitHub.

Txp Builders – finely-crafted code, design and Txp

Offline

#3 2019-05-06 12:02:25

etc
Developer
Registered: 2010-11-11
Posts: 3,341
Website

Re: A neater way of shortening a string without plugins?

You can shorten the code by adding an appropriate PHP function to PHP functions enabled in txp:evaluate advanced pref, e.g. replace=preg_replace. Than it becomes

<txp:evaluate query='replace("/(?<=^.{158}).{2,}$/", "…", <txp:excerpt escape="tags, trim, quote" />)' />

This is ugly, but I’m not aware of any clever truncate PHP function.

Offline

Board footer

Powered by FluxBB