Search code examples
asp.net-mvcjsrenderjsviews

jsviews/jsrender Converter not working on {{:...}} tag


I am attempting to use a converter to modify a string in a jsrender template, but I can't seem to get the converter to work on a tag. Using the example on JsRender API documentation Using converters for example, I have:

<script>
    $.views.converters("upper", function(val) {
        return val.toUpperCase();
    });
</script>

Then in my HTML I have {{upper:Name}} which throws an error in the console: TypeError: val is undefined, and the template does not render at all.

However, if I apply the converter directly to a string like {{upper:"This should be uppercase"}} it outputs the string in uppercase as expected.

The {{:Name}} tag works fine by itself, so why isn't the converter working with it?

In case it is relevant, this is an ASP.NET-MVC project and the JSON data rendered by the template is coming from a $.post('@Url.Action(..,..)')... response. It's working perfectly until I attempt to apply the converter to the tag. Are converters not usable in this scenario?


Solution

  • It looks like your Name property is undefined in some case.

    If you have a Name that is undefined, then {{:Name}} will render as the empty string, "" - but {{upper:Name}} will throw an error since undefined.toUpperCase() will fail.

    You can investigate by breaking on thrown errors, (or by putting a break point or debugger statement in the converter) and seeing where your undefined Name is coming from.

    You can also prevent the error getting thrown - and instead get error information rendered out - by any of the following techniques

    • write {{upper:Name onerror=true}} or {{upper:Name onerror='bad'}} (see https://www.jsviews.com/#onerror)
    • write

      $.views.converters("upper", function(val) { return val === undefined ? 'undefined' : val.toUpperCase(); });

    • write $.views.settings.debugMode(true);

    and see what output you get, to investigate further about where your undefined Name is occuring.