速度模板和 Java 字符串

Velocity Template and Java String

我开发 jira 报告 plugin.Velocity 模板在 java 字符串中显示 ascii 代码单引号或双引号。

Java代码:

主线:

    Map velocityParams = new HashMap();
    String horizontalAxis = convertKeysToWeekCategories(bugtrends.keySet());

    velocityParams.put("horizontalAxis", horizontalAxis);

convertKeysToWeekCategories 方法:

    StringBuilder build = new StringBuilder();

    for (Integer integer : keySet) {
        build.append("\'");
        build.append("W");
        build.append(integer.toString());
        build.append("\'");
        build.append(",");
    }

    String result = build.toString();

    result = result.substring(0, result.length() - 1);

    return result;

}

我用 HighChart 画画 api。

bugstrendview.vm:

<head >
    <meta charset="utf-8">
</head>

<script>AJS.$(document).ready(function(){ 


    chart = new Highcharts.Chart({

        chart: {
            type: 'spline',
            renderTo: 'container'
        },
        exporting: {
            enabled: true,
            filename: "open-bugs-trend-chart"
        },
        title: {
            text: 'Open Bugs Trend',
            x: -20 //center
        },
        subtitle: {
            text: 'results are displayed in weeks',
            x: -20 //center
        },
        xAxis: {
            categories: [$horizontalAxis],
            labels: {
                rotation: -90,
                align: 'right',
                style: {
                    fontSize: '13px',
                    fontFamily: 'Verdana, sans-serif'
                }
            }
        },

        tooltip: {

        formatter: function() {
            var myDates = $tooltipDates;
            return "<b>W"+(this.point.x+1)+"</b><br/>"+
            myDates[this.point.x]+" - "+myDates[this.point.x + 1]+
            "<br/>"+"Total Bugs : "+this.point.y ;

        },
    },


        yAxis: {
            gridLineWidth: 1,
            minorGridLineWidth: 1,
            title: {
                text: 'Number of Open Bugs'
            },
            min: 0,
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        plotOptions: {
            spline: {
                dataLabels: {
                    enabled: true
                },
                marker: {
                    enable: true
                }
            }
        },
        series: [
        {
            showInLegend: false,
            data: [$verticalAxis]
        }]
    });        });

</script>

然后在 bugstrendview.vm 类别中显示:[&#39;W1&#39;] 为错误 'Uncaught SyntaxError: Unexpected token &' 并且当然不绘制。

为什么显示单引号的ascii码?

显然 ' 被编码为 &#39;

查看此线程:

https://answers.atlassian.com/questions/24351/how-to-prevent-velocity-escape-html

WithHtml 附加到变量名应该可以防止 HTML 转义

你可以这样做:

#set($horizontalAxisWithHtml = $horizontalAxis)

然后使用$horizontalAxisWithHtml