Re: Apache Velocity : Verify if all substitutions are made
Debraj Manna <[email protected]> Tue, 13 Jun 2023 19:59:31 +0530
| Newsgroups | gmane.comp.jakarta.velocity.user |
|---|---|
| Message-ID | <CAF6DVKMTjQ86AYtHy5tjPnRo7BiMxGy8R=U_22sQAw+Oghsukg@mail.gmail.com> |
--000000000000736d4605fe03ab17 Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: quoted-printable Thanks for replying. It will work in my use case. On Tue, Jun 13, 2023 at 7:14=E2=80=AFPM Christopher Schultz < [email protected]> wrote: > Debraj, > > On 6/13/23 05:38, Debraj Manna wrote: > > Can someone let me know how I can verify a velocity context against a > > template? Basically, I want to throw some error if all variables are no= t > > substituted in the velocity template. > > > > For example, let's say I have a velocity template, card.vm > > > > card { > > type: CREDIT > > company: VISA > > name: "${firstName} ${lastName}" > > } > > > > The substitution is done like below > > > > VelocityEngine velocityEngine =3D new VelocityEngine(); > > velocityEngine.init(); > > > > Template t =3D velocityEngine.getTemplate("card.vm"); > > > > VelocityContext context =3D new VelocityContext(); > > context.put("firstName", "tuk"); > > StringWriter writer =3D new StringWriter(); > > t.merge( context, writer ); > > > > In this case, I want to throw some error specifying that lastName is no= t > > replaced in template. > > > > Does velocity provide anything for this? > > No, but it would be easy to do. Instead of using the basic > VelocityContext, wrap it in a custom one, something like this: > > public class WarningVelocityContext > extends VelocityContext > { > public Object get(String key) { > Object o =3D super.get(key); > > if(null =3D=3D o) { > throw new IllegalStateException("Key {" + key + "} has not > been set"); > } > } > } > > Then in your code, wrap the context right before merging: > > t.merge(new WarningVelocityContext(context), writer); > > Note that this will throw exceptions for *anything* that's not found for > any reason. If you try something like: > > $someObject.method() > > And "someObject" is null, then you'll get an error. It may be difficult > to tell the difference between the things you "care about" and the > things you do not. If you have a simple use-case, then probably this > will work. > > -chris > > --------------------------------------------------------------------- > To unsubscribe, e-mail: [email protected] > For additional commands, e-mail: [email protected] > > --000000000000736d4605fe03ab17--