This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch 
gh-readonly-queue/main/pr-9419-4b4a0c386d81a247bd1d49b7f686fc93e509e2f9
in repository https://gitbox.apache.org/repos/asf/texera.git

commit 0e9c48b4a8e2dfb1ac317ae22b7f12f1d1792139
Author: Xinyuan Lin <[email protected]>
AuthorDate: Mon Nov 16 02:42:11 2026 +0000

    refactor(workflow-operator): share chart code fragments (#9419)
    
    ### What changes were proposed in this PR?
    
    Share static Python chart bodies between runtime and export, and
    centralize repeated standalone error renderers and output-writing
    fragments. This removes 211 net lines across 46 visualization
    descriptors and two shared helpers. The generated runtime Python and
    chart messages are unchanged; the exported Gauge, Radar and Tree scripts
    now also carry the comment and blank lines of the bodies they share with
    the runtime.
    
    ### Any related issues, documentation, discussions?
    
    Closes #9418.
    
    ### How was this PR tested?
    
    ```sh
    sbt "WorkflowOperator/scalafix --check" "WorkflowOperator/Test/scalafix 
--check" scalafmtCheckAll
    ```
    
    408 tests passed across 55 suites, with one existing pending case:
    
    <details>
    <summary>Exact test command</summary>
    
    ```sh
    sbt "WorkflowOperator/testOnly *DotPlotOpDescSpec 
*ScatterMatrixChartOpDescSpec *BarChartOpDescSpec *BoxViolinPlotOpDescSpec 
*BubbleChartOpDescSpec *BulletChartOpDescSpec *BulletChartStepDefinitionSpec 
*CandlestickChartOpDescSpec *CarpetPlotOpDescSpec *ChoroplethMapOpDescSpec 
*BandConfigSpec *ContinuousErrorBandsOpDescSpec *ContourPlotOpDescSpec 
*DendrogramOpDescSpec *DumbbellDotConfigSpec *DumbbellPlotOpDescSpec 
*ECDFPlotOpDescSpec *FigureFactoryTableConfigSpec *FigureFactoryTableOpD [...]
    ```
    
    </details>
    
    The runtime and exported scripts of every registered visualization
    descriptor at its defaults, plus 11 configured Gauge, Radar, Tree,
    NestedTable, WordCloud, Hierarchy and Icicle cases, were captured on the
    base and on this branch. All match byte for byte (or raise the same
    error where a default leaves a required field empty), except the Gauge,
    Radar and Tree exports, which gain only the 4 blank lines, 1 comment
    line and 6 comment lines of their shared bodies.
    
    ### Was this PR authored or co-authored using generative AI tooling?
    
    Generated-by: Codex (GPT-6) and Claude Code (Claude Opus 5.5)
---
 .../visualization/DotPlot/DotPlotOpDesc.scala      |  10 +-
 .../IcicleChart/IcicleChartOpDesc.scala            |  10 +-
 .../visualization/PythonCodeFragment.scala         |  29 ++++
 .../ScatterMatrixChartOpDesc.scala                 |   5 +-
 .../visualization/StandaloneChartCode.scala        |  47 ++++++
 .../visualization/barChart/BarChartOpDesc.scala    |  10 +-
 .../boxViolinPlot/BoxViolinPlotOpDesc.scala        |  10 +-
 .../bubbleChart/BubbleChartOpDesc.scala            |  10 +-
 .../bulletChart/BulletChartOpDesc.scala            |   7 +-
 .../candlestickChart/CandlestickChartOpDesc.scala  |   5 +-
 .../carpetPlot/CarpetPlotOpDesc.scala              |   5 +-
 .../choroplethMap/ChoroplethMapOpDesc.scala        |  10 +-
 .../ContinuousErrorBandsOpDesc.scala               |  13 +-
 .../contourPlot/ContourPlotOpDesc.scala            |  10 +-
 .../dendrogram/DendrogramOpDesc.scala              |  10 +-
 .../dumbbellPlot/DumbbellPlotOpDesc.scala          |  10 +-
 .../visualization/ecdfPlot/ECDFPlotOpDesc.scala    |  19 +--
 .../FigureFactoryTableOpDesc.scala                 |  14 +-
 .../filledAreaPlot/FilledAreaPlotOpDesc.scala      |   5 +-
 .../funnelPlot/FunnelPlotOpDesc.scala              |  13 +-
 .../ganttChart/GanttChartOpDesc.scala              |  14 +-
 .../gaugeChart/GaugeChartOpDesc.scala              | 120 ++++++-------
 .../visualization/heatMap/HeatMapOpDesc.scala      |  13 +-
 .../hierarchychart/HierarchyChartOpDesc.scala      |  10 +-
 .../histogram/HistogramChartOpDesc.scala           |  13 +-
 .../histogram2d/Histogram2DOpDesc.scala            |  11 +-
 .../visualization/lineChart/LineChartOpDesc.scala  |  13 +-
 .../nestedTable/NestedTableOpDesc.scala            |  99 +++++------
 .../networkGraph/NetworkGraphOpDesc.scala          |  16 +-
 .../ParallelCoordinatesPlotOpDesc.scala            |  16 +-
 .../visualization/pieChart/PieChartOpDesc.scala    |  19 +--
 .../polarChart/PolarChartOpDesc.scala              |   5 +-
 .../quiverPlot/QuiverPlotOpDesc.scala              |  13 +-
 .../radarChart/RadarChartOpDesc.scala              |  16 +-
 .../visualization/radarPlot/RadarPlotOpDesc.scala  | 179 +++++++-------------
 .../rangeSlider/RangeSliderOpDesc.scala            |  16 +-
 .../sankeyDiagram/SankeyDiagramOpDesc.scala        |  19 +--
 .../scatter3DChart/Scatter3dChartOpDesc.scala      |  13 +-
 .../scatterplot/ScatterplotOpDesc.scala            |  19 +--
 .../stripChart/StripChartOpDesc.scala              |   5 +-
 .../tablesChart/TablesPlotOpDesc.scala             |  10 +-
 .../ternaryContour/TernaryContourOpDesc.scala      |  19 +--
 .../ternaryPlot/TernaryPlotOpDesc.scala            |  19 +--
 .../timeSeriesplot/TimeSeriesOpDesc.scala          |  11 +-
 .../visualization/treeplot/TreePlotOpDesc.scala    | 185 ++++++++-------------
 .../waterfallChart/WaterfallChartOpDesc.scala      |  13 +-
 .../windRoseChart/WindRoseChartOpDesc.scala        |  16 +-
 .../visualization/wordCloud/WordCloudOpDesc.scala  |  19 +--
 48 files changed, 481 insertions(+), 692 deletions(-)

diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/DotPlot/DotPlotOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/DotPlot/DotPlotOpDesc.scala
index c6da62bb8d..46e8e2a782 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/DotPlot/DotPlotOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/DotPlot/DotPlotOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.DotPlot
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaTitle
 import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{
@@ -101,10 +102,7 @@ class DotPlotOpDesc extends PythonVisualizationOpDesc with 
PlotlyStandaloneCode
     // to the terminal alone left that file absent. render_error's continuation
     // line keeps the runtime path's indentation, since the HTML is 
triple-quoted
     // and those spaces reach the browser.
-    s"""def render_error(error_msg):
-       |    return '''<h1>DotPlot is not available.</h1>
-       |                  <p>Reasons are: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("DotPlot is not available.", plural = true)}
        |
        |def fail(error_msg):
        |    with open(outputHtml, "w", encoding="utf-8") as output:
@@ -122,9 +120,7 @@ class DotPlotOpDesc extends PythonVisualizationOpDesc with 
PlotlyStandaloneCode
        |                       
color_discrete_sequence=px.colors.qualitative.Dark2)
        |        fig.update_traces(marker=dict(size=12, line=dict(width=2, 
color='DarkSlateGrey')))
        |        fig.update_layout(margin=dict(t=0, b=0, l=0, r=0))
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("Dot plot saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Dot plot")}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/IcicleChart/IcicleChartOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/IcicleChart/IcicleChartOpDesc.scala
index 1e07ec9097..557af3a7f2 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/IcicleChart/IcicleChartOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/IcicleChart/IcicleChartOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.IcicleChart
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{
@@ -134,10 +135,7 @@ class IcicleChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneC
     // to the terminal alone left that file absent. render_error's continuation
     // line keeps the runtime path's indentation, since the HTML is 
triple-quoted
     // and those spaces reach the browser. chart_df is a copy: the input can 
feed another branch.
-    s"""def render_error(error_msg):
-       |    return '''<h1>Icicle chart is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("Icicle chart is not available.")}
        |
        |def fail(error_msg):
        |    with open(outputHtml, "w", encoding="utf-8") as output:
@@ -157,9 +155,7 @@ class IcicleChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneC
        |                         color=$valueLit, hover_data=[$attributes],
        |                         color_continuous_scale='RdBu')
        |        fig.update_layout(margin=dict(l=0, r=0, b=0, t=0))
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("Icicle chart saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Icicle chart")}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/PythonCodeFragment.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/PythonCodeFragment.scala
new file mode 100644
index 0000000000..3ee6a7a176
--- /dev/null
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/PythonCodeFragment.scala
@@ -0,0 +1,29 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.texera.amber.operator.visualization
+
+private[visualization] object PythonCodeFragment {
+  def render(code: String, indent: Int): String =
+    code.stripMargin.linesIterator
+      .map { line =>
+        if (line.isEmpty) line else (" " * indent) + line
+      }
+      .mkString("\n")
+}
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ScatterMatrixChart/ScatterMatrixChartOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ScatterMatrixChart/ScatterMatrixChartOpDesc.scala
index 592a2bf50a..a1e38990d7 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ScatterMatrixChart/ScatterMatrixChartOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ScatterMatrixChart/ScatterMatrixChartOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.ScatterMatrixChart
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{
@@ -116,8 +117,6 @@ class ScatterMatrixChartOpDesc extends 
PythonVisualizationOpDesc with PlotlyStan
     // here printed to stdout without writing any output at all.
     s"""fig = px.scatter_matrix(in1df, dimensions=[$dimensions], 
color=${pyStringLiteral(color)})
        |fig.update_layout(margin=dict(t=0, b=0, l=0, r=0))
-       |fig.write_json(outputJson)
-       |fig.write_html(outputHtml)
-       |print("Scatter matrix saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Scatter matrix", indent = 0)}""".stripMargin
   }
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/StandaloneChartCode.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/StandaloneChartCode.scala
new file mode 100644
index 0000000000..3a6a201fc1
--- /dev/null
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/StandaloneChartCode.scala
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.texera.amber.operator.visualization
+
+import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.pyStringLiteral
+
+private[visualization] object StandaloneChartCode {
+  def standaloneError(title: String, plural: Boolean = false, typed: Boolean = 
false): String =
+    s"""def render_error(error_msg)${if (typed) " -> str" else ""}:
+       |    return '''<h1>$title</h1>
+       |                  <p>${if (plural) "Reasons are" else "Reason is"}: {} 
</p>
+       |               '''.format(error_msg)""".stripMargin
+
+  def standaloneFigure(label: String, indent: Int = 8, bothOutputs: Boolean = 
false): String =
+    PythonCodeFragment.render(
+      s"""fig.write_json(outputJson)
+         |fig.write_html(outputHtml)
+         |print(${pyStringLiteral(label + " saved to ")} + ${if (bothOutputs)
+        """outputJson + " and " + outputHtml"""
+      else "outputHtml"})""",
+      indent
+    )
+
+  def standaloneErrorPage(message: String, indent: Int = 4, handle: String = 
"output"): String =
+    PythonCodeFragment.render(
+      s"""with open(outputHtml, "w", encoding="utf-8") as $handle:
+         |    $handle.write(render_error(${pyStringLiteral(message)}))""",
+      indent
+    )
+}
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/barChart/BarChartOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/barChart/BarChartOpDesc.scala
index 309e463112..ef360bbaa4 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/barChart/BarChartOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/barChart/BarChartOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.barChart
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{
@@ -168,10 +169,7 @@ class BarChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCode
     // line keeps the runtime path's indentation, since the HTML is 
triple-quoted
     // and those spaces reach the browser. Empty is checked before the dropna, 
since an empty
     // table read back from JSONL has no columns to name, and chart_df keeps 
the input whole.
-    s"""def render_error(error_msg):
-       |    return '''<h1>Bar chart is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("Bar chart is not available.")}
        |
        |def fail(error_msg):
        |    with open(outputHtml, "w", encoding="utf-8") as output:
@@ -189,8 +187,6 @@ class BarChartOpDesc extends PythonVisualizationOpDesc with 
PlotlyStandaloneCode
        |    else:
        |        fig = go.Figure(px.bar(chart_df, $barArgs))
        |        fig.update_layout(margin=dict(l=0, r=0, t=0, b=0))
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("Bar chart saved to " + outputJson + " and " + 
outputHtml)""".stripMargin
+       |${standaloneFigure("Bar chart", bothOutputs = true)}""".stripMargin
   }
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/boxViolinPlot/BoxViolinPlotOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/boxViolinPlot/BoxViolinPlotOpDesc.scala
index 3729713667..10c5eb5b4d 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/boxViolinPlot/BoxViolinPlotOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/boxViolinPlot/BoxViolinPlotOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.boxViolinPlot
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, 
JsonPropertyDescription, JsonPropertyOrder}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{
@@ -158,10 +159,7 @@ class BoxViolinPlotOpDesc extends 
PythonVisualizationOpDesc with PlotlyStandalon
     // to the terminal alone left that file absent. render_error's continuation
     // line keeps the runtime path's indentation, since the HTML is 
triple-quoted
     // and those spaces reach the browser. chart_df keeps the input whole for 
other branches.
-    s"""def render_error(error_msg):
-       |    return '''<h1>Box/Violin Plot is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("Box/Violin Plot is not available.")}
        |
        |def fail(error_msg):
        |    with open(outputHtml, "w", encoding="utf-8") as output:
@@ -187,9 +185,7 @@ class BoxViolinPlotOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandalon
        |                fig = px.box(chart_df, y=$valueLit, boxmode="overlay", 
points='all')
        |        
fig.update_traces(quartilemethod=${pyStringLiteral(quartileMethod)}, col=1)
        |        fig.update_layout(margin=dict(t=0, b=0, l=0, r=0))
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("Box/Violin Plot saved to " + outputJson + " and " + 
outputHtml)""".stripMargin
+       |${standaloneFigure("Box/Violin Plot", bothOutputs = 
true)}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/bubbleChart/BubbleChartOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/bubbleChart/BubbleChartOpDesc.scala
index 2d309a7e20..e13610f528 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/bubbleChart/BubbleChartOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/bubbleChart/BubbleChartOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.bubbleChart
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{
@@ -169,10 +170,7 @@ class BubbleChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneC
     // render_error's continuation line keeps the runtime path's indentation, 
since
     // the HTML is triple-quoted and those spaces reach the browser. chart_df 
keeps the
     // input whole for other branches.
-    s"""def render_error(error_msg):
-       |    return '''<h1>TreeMap is not available.</h1>
-       |                  <p>Reasons are: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("TreeMap is not available.", plural = true)}
        |
        |def fail(error_msg):
        |    with open(outputHtml, "w", encoding="utf-8") as output:
@@ -194,8 +192,6 @@ class BubbleChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneC
        |            size_max=100$colorArg
        |        ))
        |        fig.update_layout(margin=dict(l=0, r=0, b=0, t=0))
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("Bubble chart saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Bubble chart")}""".stripMargin
   }
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/bulletChart/BulletChartOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/bulletChart/BulletChartOpDesc.scala
index 7191ce40cb..530ecb7924 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/bulletChart/BulletChartOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/bulletChart/BulletChartOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.bulletChart
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.fasterxml.jackson.databind.annotation.JsonDeserialize
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
@@ -283,8 +284,7 @@ class BulletChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneC
        |    return valid_steps, step_errors
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("Input table is empty."))
+       |${standaloneErrorPage("Input table is empty.")}
        |else:
        |    try:
        |        value_col = $valueLit
@@ -295,8 +295,7 @@ class BulletChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneC
        |        else:
        |            table = in1df.dropna(subset=[value_col])
        |            if table.empty:
-       |                with open(outputHtml, "w", encoding="utf-8") as output:
-       |                    output.write(render_error("No valid data rows 
found after dropping nulls."))
+       |${standaloneErrorPage("No valid data rows found after dropping 
nulls.", indent = 16)}
        |            else:
        |                threshold_val = $thresholdExpr
        |                valid_steps, step_errors = 
generate_valid_steps($stepsExpr)
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/candlestickChart/CandlestickChartOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/candlestickChart/CandlestickChartOpDesc.scala
index 4ecfa34f5b..2e5182e84d 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/candlestickChart/CandlestickChartOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/candlestickChart/CandlestickChartOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.candlestickChart
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaTitle
 import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{
@@ -121,8 +122,6 @@ class CandlestickChartOpDesc extends 
PythonVisualizationOpDesc with PlotlyStanda
        |    close=in1df[${pyStringLiteral(close)}]
        |)])
        |fig.update_layout(title='Candlestick Chart')
-       |fig.write_json(outputJson)
-       |fig.write_html(outputHtml)
-       |print("Candlestick chart saved to " + outputJson + " and " + 
outputHtml)""".stripMargin
+       |${standaloneFigure("Candlestick chart", indent = 0, bothOutputs = 
true)}""".stripMargin
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/carpetPlot/CarpetPlotOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/carpetPlot/CarpetPlotOpDesc.scala
index 7113204278..d9f633c91a 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/carpetPlot/CarpetPlotOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/carpetPlot/CarpetPlotOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.carpetPlot
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{
@@ -166,9 +167,7 @@ class CarpetPlotOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCo
        |            except Exception as e:
        |                _write_page(f"<h3>Error generating carpet plot: 
{str(e)}</h3>")
        |            else:
-       |                fig.write_json(outputJson)
-       |                fig.write_html(outputHtml)
-       |                print("Carpet plot saved to " + outputJson + " and " + 
outputHtml)""".stripMargin
+       |${standaloneFigure("Carpet plot", indent = 16, bothOutputs = 
true)}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/choroplethMap/ChoroplethMapOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/choroplethMap/ChoroplethMapOpDesc.scala
index 974747a84f..3932e964a3 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/choroplethMap/ChoroplethMapOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/choroplethMap/ChoroplethMapOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.choroplethMap
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{
@@ -132,10 +133,7 @@ class ChoroplethMapOpDesc extends 
PythonVisualizationOpDesc with PlotlyStandalon
     // to the terminal alone left that file absent. render_error's continuation
     // line keeps the runtime path's indentation, since the HTML is 
triple-quoted
     // and those spaces reach the browser. chart_df keeps the input whole for 
other branches.
-    s"""def render_error(error_msg):
-       |    return '''<h1>Choropleth map is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("Choropleth map is not available.")}
        |
        |def fail(error_msg):
        |    with open(outputHtml, "w", encoding="utf-8") as output:
@@ -151,8 +149,6 @@ class ChoroplethMapOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandalon
        |    else:
        |        fig = px.choropleth(chart_df, locations=$locationsLit, 
color=$colorLit, color_continuous_scale=px.colors.sequential.Plasma)
        |        fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("Choropleth map saved to " + outputJson + " and " + 
outputHtml)""".stripMargin
+       |${standaloneFigure("Choropleth map", bothOutputs = 
true)}""".stripMargin
   }
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/continuousErrorBands/ContinuousErrorBandsOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/continuousErrorBands/ContinuousErrorBandsOpDesc.scala
index a664e2bca5..3a61f717dd 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/continuousErrorBands/ContinuousErrorBandsOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/continuousErrorBands/ContinuousErrorBandsOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.continuousErrorBands
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaTitle
 import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{
@@ -205,14 +206,10 @@ class ContinuousErrorBandsOpDesc extends 
PythonVisualizationOpDesc with PlotlySt
     // The empty-input branch mirrors generatePythonCode's `if table.empty`
     // guard: without it the traces index columns of a frame that has none, and
     // an empty input silently renders a blank chart instead of saying why.
-    s"""def render_error(error_msg):
-       |    return '''<h1>Continuous Error Bands is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("Continuous Error Bands is not available.")}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("input table is empty."))
+       |${standaloneErrorPage("input table is empty.")}
        |else:
        |    fig = go.Figure()
        |$indentedTraces
@@ -220,8 +217,6 @@ class ContinuousErrorBandsOpDesc extends 
PythonVisualizationOpDesc with PlotlySt
        |                      xaxis_title=${pyStringLiteral(xLabel)},
        |                      yaxis_title=${pyStringLiteral(yLabel)},
        |                      hovermode="x")
-       |    fig.write_json(outputJson)
-       |    fig.write_html(outputHtml)
-       |    print("Continuous error bands saved to " + outputJson + " and " + 
outputHtml)""".stripMargin
+       |${standaloneFigure("Continuous error bands", indent = 4, bothOutputs = 
true)}""".stripMargin
   }
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/contourPlot/ContourPlotOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/contourPlot/ContourPlotOpDesc.scala
index 799dcd81c0..c023b3405f 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/contourPlot/ContourPlotOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/contourPlot/ContourPlotOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.contourPlot
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.fasterxml.jackson.databind.annotation.JsonDeserialize
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
@@ -159,10 +160,7 @@ class ContourPlotOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneC
     s"""import numpy as np
        |from scipy.interpolate import griddata
        |
-       |def render_error(error_msg):
-       |    return '''<h1>Contour plot is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+       |${standaloneError("Contour plot is not available.")}
        |
        |def _write_error(message):
        |    with open(outputHtml, "w", encoding="utf-8") as output:
@@ -199,9 +197,7 @@ class ContourPlotOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneC
        |            colorbar_title=${pyStringLiteral(z)}
        |        ))
        |        fig.update_layout(title='Contour Plot')
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("Contour plot saved to " + outputJson + " and " + 
outputHtml)""".stripMargin
+       |${standaloneFigure("Contour plot", bothOutputs = true)}""".stripMargin
 }
 
 object ContourPlotOpDesc {
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/dendrogram/DendrogramOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/dendrogram/DendrogramOpDesc.scala
index 593fa39e24..16ff19e238 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/dendrogram/DendrogramOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/dendrogram/DendrogramOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.dendrogram
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.fasterxml.jackson.databind.annotation.JsonDeserialize
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
@@ -151,10 +152,7 @@ class DendrogramOpDesc extends PythonVisualizationOpDesc {
     s"""import numpy as np
        |import plotly.figure_factory as ff
        |
-       |def render_error(error_msg):
-       |    return '''<h1>Dendrogram is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+       |${standaloneError("Dendrogram is not available.")}
        |
        |def _write_error(message):
        |    with open(outputHtml, "w", encoding="utf-8") as output:
@@ -175,9 +173,7 @@ class DendrogramOpDesc extends PythonVisualizationOpDesc {
        |        labels = chart_df[${pyStringLiteral(labels)}].tolist()
        |        fig = ff.create_dendrogram(data, labels=labels, 
color_threshold=$thresholdExpr)
        |        fig.update_layout(yaxis_title="Linkage Distance", 
margin=dict(l=0, r=0, b=0, t=0))
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("Dendrogram saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Dendrogram")}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/dumbbellPlot/DumbbellPlotOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/dumbbellPlot/DumbbellPlotOpDesc.scala
index 127e01d30c..d9092583ee 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/dumbbellPlot/DumbbellPlotOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/dumbbellPlot/DumbbellPlotOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.dumbbellPlot
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{
@@ -204,10 +205,7 @@ class DumbbellPlotOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandalone
       else ""
     s"""import plotly.graph_objects as go
        |
-       |def render_error(error_msg):
-       |    return '''<h1>DumbbellPlot is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+       |${standaloneError("DumbbellPlot is not available.")}
        |
        |table = in1df
        |_error = None
@@ -254,8 +252,6 @@ class DumbbellPlotOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandalone
        |                                     mode='markers',
        |                                     name=entity + ' ' + dotColumn,
        |                                     marker=dict(color='black', 
size=5)))
-       |    fig.write_json(outputJson)
-       |    fig.write_html(outputHtml)
-       |    print("Dumbbell plot saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Dumbbell plot", indent = 4)}""".stripMargin
   }
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ecdfPlot/ECDFPlotOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ecdfPlot/ECDFPlotOpDesc.scala
index cad20709df..3331ad6f13 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ecdfPlot/ECDFPlotOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ecdfPlot/ECDFPlotOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.ecdfPlot
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import org.apache.texera.amber.operator.visualization.PlotlyStandaloneCode
@@ -200,27 +201,23 @@ class ECDFPlotOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCode
     if (showMarkers) args += "markers=True"
     if (marginal != "none") args += 
s"""marginal=${pyStringLiteral(marginal)}"""
 
-    s"""def render_error(error_msg):
-       |    return '''<h1>Empirical cumulative distribution plot is not 
available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("Empirical cumulative distribution plot is not 
available.")}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("input table is empty."))
+       |${standaloneErrorPage("input table is empty.")}
        |else:
        |    table = in1df.dropna(subset=$requiredColsLiteral).copy()
        |    table[$valueLit] = pd.to_numeric(table[$valueLit], errors='coerce')
        |    table.dropna(subset=[$valueLit], inplace=True)
        |    if table.empty:
-       |        with open(outputHtml, "w", encoding="utf-8") as output:
-       |            output.write(render_error("no valid rows left after 
removing missing or non-numeric values."))
+       |${standaloneErrorPage(
+      "no valid rows left after removing missing or non-numeric values.",
+      indent = 8
+    )}
        |    else:
        |        fig = px.ecdf(${args.mkString(", ")})
        |        fig.update_layout(margin=dict(l=0, r=0, t=30, b=0))
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("ECDF plot saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("ECDF plot")}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/figureFactoryTable/FigureFactoryTableOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/figureFactoryTable/FigureFactoryTableOpDesc.scala
index 36c2790c5f..5ac5c23eda 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/figureFactoryTable/FigureFactoryTableOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/figureFactoryTable/FigureFactoryTableOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.figureFactoryTable
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{
@@ -152,13 +153,14 @@ class FigureFactoryTableOpDesc extends 
PythonVisualizationOpDesc {
        |    )
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("input table is empty."))
+       |${standaloneErrorPage("input table is empty.")}
        |else:
        |    table = in1df.dropna(subset=[$attributes])
        |    if table.empty:
-       |        with open(outputHtml, "w", encoding="utf-8") as output:
-       |            output.write(render_error("value column contains only 
non-positive numbers or nulls."))
+       |${standaloneErrorPage(
+      "value column contains only non-positive numbers or nulls.",
+      indent = 8
+    )}
        |    else:
        |        filtered_table = table[[$attributes]]
        |        headers = filtered_table.columns.tolist()
@@ -170,8 +172,6 @@ class FigureFactoryTableOpDesc extends 
PythonVisualizationOpDesc {
        |        for i in range(len(fig.layout.annotations)):
        |            fig.layout.annotations[i].font.size = $fontSize
        |        fig.update_layout(margin=dict(l=0, r=0, b=0, t=0))
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("Figure factory table saved to " + 
outputHtml)""".stripMargin
+       |${standaloneFigure("Figure factory table")}""".stripMargin
   }
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/filledAreaPlot/FilledAreaPlotOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/filledAreaPlot/FilledAreaPlotOpDesc.scala
index 541fe60981..081d80a17d 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/filledAreaPlot/FilledAreaPlotOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/filledAreaPlot/FilledAreaPlotOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.filledAreaPlot
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{
@@ -229,9 +230,7 @@ class FilledAreaPlotOpDesc extends 
PythonVisualizationOpDesc with PlotlyStandalo
        |if error == "":
        |    fig = px.area(in1df, x=$xLit, 
y=$yLit$colorArg$facetColumnArg$lineGroupArg$patternParam)
        |    fig.update_layout(margin=dict(l=0, r=0, b=0, t=0))
-       |    fig.write_json(outputJson)
-       |    fig.write_html(outputHtml)
-       |    print("Filled area plot saved to " + outputHtml)
+       |${standaloneFigure("Filled area plot", indent = 4)}
        |elif error == "X attributes not shared across groups":
        |    with open(outputHtml, "w", encoding="utf-8") as output:
        |        output.write('''<h1>Plot is not available, because:</h1>
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/funnelPlot/FunnelPlotOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/funnelPlot/FunnelPlotOpDesc.scala
index 1e0c6d81cd..3a8178a484 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/funnelPlot/FunnelPlotOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/funnelPlot/FunnelPlotOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.funnelPlot
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaTitle
 import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{
@@ -113,14 +114,10 @@ class FunnelPlotOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCo
     val colorArg = if (color.nonEmpty) s""", 
color=${pyStringLiteral(color)}""" else ""
     val xLit = pyStringLiteral(x)
     val yLit = pyStringLiteral(y)
-    s"""def render_error(error_msg):
-       |    return '''<h1>Chart is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("Chart is not available.")}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("input table is empty."))
+       |${standaloneErrorPage("input table is empty.")}
        |else:
        |    fig = go.Figure(px.funnel(in1df, x=$xLit, y=$yLit$colorArg))
        |    fig.update_layout(
@@ -130,9 +127,7 @@ class FunnelPlotOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCo
        |        ),
        |        margin=dict(t=0, b=0, l=0, r=0)
        |    )
-       |    fig.write_json(outputJson)
-       |    fig.write_html(outputHtml)
-       |    print("Funnel plot saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Funnel plot", indent = 4)}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ganttChart/GanttChartOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ganttChart/GanttChartOpDesc.scala
index 1c74e8e377..74f8284682 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ganttChart/GanttChartOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ganttChart/GanttChartOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.ganttChart
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{
@@ -157,20 +158,19 @@ class GanttChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCo
        |               '''.format(error_msg)
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("Input table is empty."))
+       |${standaloneErrorPage("Input table is empty.")}
        |else:
        |    table = in1df[(in1df[$startLit].notnull()) & 
(in1df[$finishLit].notnull())$optionalFilter].copy()
        |    if table.empty:
-       |        with open(outputHtml, "w", encoding="utf-8") as output:
-       |            output.write(render_error("One or more of your input 
columns have all missing values"))
+       |${standaloneErrorPage(
+      "One or more of your input columns have all missing values",
+      indent = 8
+    )}
        |    else:
        |        fig = px.timeline(table, x_start=$startLit, x_end=$finishLit, 
y=$taskLit$colorSetting$patternSetting)
        |        fig.update_yaxes(autorange='reversed')
        |        fig.update_layout(margin=dict(t=0, b=0, l=0, r=0))
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("Gantt chart saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Gantt chart")}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/gaugeChart/GaugeChartOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/gaugeChart/GaugeChartOpDesc.scala
index 9238fdee9a..1324d41b8f 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/gaugeChart/GaugeChartOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/gaugeChart/GaugeChartOpDesc.scala
@@ -18,6 +18,7 @@
 
 package org.apache.texera.amber.operator.visualization.gaugeChart
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.fasterxml.jackson.databind.annotation.JsonDeserialize
 import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaTitle
@@ -133,42 +134,7 @@ class GaugeChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCo
          |            html_chunks = []
          |            for _, row in table.iterrows():
          |                try:
-         |                    actual = float(row[gauge_value])
-         |                    max_val = actual
-         |                    if delta_ref is not None:
-         |                        max_val = max(max_val, delta_ref)
-         |                    if threshold_val is not None:
-         |                        max_val = max(max_val, threshold_val)
-         |                    if steps_list:
-         |                        for r in steps_list:
-         |                            max_val = max(max_val, r["range"][1])
-         |
-         |                    gauge_config = {'axis': {'range': [None, max_val 
* 1.2]}}
-         |                    if steps_list:
-         |                        gauge_config['steps'] = steps_list
-         |                    if threshold_val is not None:
-         |                        gauge_config['threshold'] = {
-         |                            "value": threshold_val,
-         |                            "line": {"color": "red", "width": 3},
-         |                            "thickness": 0.75
-         |                        }
-         |
-         |                    mode_parts = ["number", "gauge"]
-         |                    if delta_ref is not None:
-         |                        mode_parts.append("delta")
-         |                    mode = "+".join(mode_parts)
-         |                    delta_config = {"reference": delta_ref} if 
delta_ref is not None else None
-         |
-         |                    fig = go.Figure(go.Indicator(
-         |                        mode=mode,
-         |                        value=actual,
-         |                        delta=delta_config,
-         |                        gauge=gauge_config,
-         |                        domain={"x": [0, 1], "y": [0, 1]},
-         |                        title={"text": gauge_value}
-         |                    ))
-         |
-         |                    fig.update_layout(margin=dict(l=20, r=20, b=40, 
t=60), height=250)
+         |${GaugeChartPython.body(20)}
          |                    html_chunk = pio.to_html(fig, 
include_plotlyjs='cdn', auto_play=False)
          |
          |                    if hasattr(self, 'step_errors') and 
self.step_errors:
@@ -213,8 +179,7 @@ class GaugeChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCo
        |    return colors
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("Input table is empty."))
+       |${standaloneErrorPage("Input table is empty.")}
        |else:
        |    try:
        |        gauge_value = $valueLit
@@ -222,8 +187,7 @@ class GaugeChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCo
        |        threshold_val = $thresholdExpr
        |        table = in1df.dropna(subset=[gauge_value])
        |        if table.empty:
-       |            with open(outputHtml, "w", encoding="utf-8") as output:
-       |                output.write(render_error("No non-null rows found for 
the value column."))
+       |${standaloneErrorPage("No non-null rows found for the value column.", 
indent = 12)}
        |        else:
        |            valid_steps = $stepsExpr
        |            step_colors = generate_gray_gradient(len(valid_steps))
@@ -239,38 +203,7 @@ class GaugeChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCo
        |            figs = []
        |            for _, row in table.iterrows():
        |                try:
-       |                    actual = float(row[gauge_value])
-       |                    max_val = actual
-       |                    if delta_ref is not None:
-       |                        max_val = max(max_val, delta_ref)
-       |                    if threshold_val is not None:
-       |                        max_val = max(max_val, threshold_val)
-       |                    if steps_list:
-       |                        for r in steps_list:
-       |                            max_val = max(max_val, r["range"][1])
-       |                    gauge_config = {'axis': {'range': [None, max_val * 
1.2]}}
-       |                    if steps_list:
-       |                        gauge_config['steps'] = steps_list
-       |                    if threshold_val is not None:
-       |                        gauge_config['threshold'] = {
-       |                            "value": threshold_val,
-       |                            "line": {"color": "red", "width": 3},
-       |                            "thickness": 0.75
-       |                        }
-       |                    mode_parts = ["number", "gauge"]
-       |                    if delta_ref is not None:
-       |                        mode_parts.append("delta")
-       |                    mode = "+".join(mode_parts)
-       |                    delta_config = {"reference": delta_ref} if 
delta_ref is not None else None
-       |                    fig = go.Figure(go.Indicator(
-       |                        mode=mode,
-       |                        value=actual,
-       |                        delta=delta_config,
-       |                        gauge=gauge_config,
-       |                        domain={"x": [0, 1], "y": [0, 1]},
-       |                        title={"text": gauge_value}
-       |                    ))
-       |                    fig.update_layout(margin=dict(l=20, r=20, b=40, 
t=60), height=250)
+       |${GaugeChartPython.body(20)}
        |                    figs.append(fig)
        |                    html_chunks.append(pio.to_html(fig, 
include_plotlyjs='cdn', auto_play=False))
        |                except Exception as e:
@@ -289,3 +222,46 @@ class GaugeChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCo
        |            output.write(render_error(f"General error: 
{str(e)}"))""".stripMargin
   }
 }
+
+private object GaugeChartPython {
+  def body(indent: Int): String =
+    org.apache.texera.amber.operator.visualization.PythonCodeFragment.render(
+      """|actual = float(row[gauge_value])
+       |max_val = actual
+       |if delta_ref is not None:
+       |    max_val = max(max_val, delta_ref)
+       |if threshold_val is not None:
+       |    max_val = max(max_val, threshold_val)
+       |if steps_list:
+       |    for r in steps_list:
+       |        max_val = max(max_val, r["range"][1])
+       |
+       |gauge_config = {'axis': {'range': [None, max_val * 1.2]}}
+       |if steps_list:
+       |    gauge_config['steps'] = steps_list
+       |if threshold_val is not None:
+       |    gauge_config['threshold'] = {
+       |        "value": threshold_val,
+       |        "line": {"color": "red", "width": 3},
+       |        "thickness": 0.75
+       |    }
+       |
+       |mode_parts = ["number", "gauge"]
+       |if delta_ref is not None:
+       |    mode_parts.append("delta")
+       |mode = "+".join(mode_parts)
+       |delta_config = {"reference": delta_ref} if delta_ref is not None else 
None
+       |
+       |fig = go.Figure(go.Indicator(
+       |    mode=mode,
+       |    value=actual,
+       |    delta=delta_config,
+       |    gauge=gauge_config,
+       |    domain={"x": [0, 1], "y": [0, 1]},
+       |    title={"text": gauge_value}
+       |))
+       |
+       |fig.update_layout(margin=dict(l=20, r=20, b=40, t=60), height=250)""",
+      indent
+    )
+}
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/heatMap/HeatMapOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/heatMap/HeatMapOpDesc.scala
index 8d0ae09e5a..085f1adc99 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/heatMap/HeatMapOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/heatMap/HeatMapOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.heatMap
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaTitle
 import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{
@@ -109,21 +110,15 @@ class HeatMapOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCode
     val valueLit = pyStringLiteral(value)
     val xLit = pyStringLiteral(x)
     val yLit = pyStringLiteral(y)
-    s"""def render_error(error_msg):
-       |    return '''<h1>Chart is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("Chart is not available.")}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("input table is empty."))
+       |${standaloneErrorPage("input table is empty.")}
        |else:
        |    heatmap = go.Heatmap(z=in1df[$valueLit], x=in1df[$xLit], 
y=in1df[$yLit])
        |    layout = go.Layout(margin=dict(l=0, r=0, b=0, t=0))
        |    fig = go.Figure(data=[heatmap], layout=layout)
-       |    fig.write_json(outputJson)
-       |    fig.write_html(outputHtml)
-       |    print("Heatmap saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Heatmap", indent = 4)}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/hierarchychart/HierarchyChartOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/hierarchychart/HierarchyChartOpDesc.scala
index e194ecca9b..d216fd3473 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/hierarchychart/HierarchyChartOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/hierarchychart/HierarchyChartOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.hierarchychart
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{
@@ -139,10 +140,7 @@ class HierarchyChartOpDesc extends 
PythonVisualizationOpDesc with PlotlyStandalo
     // to the terminal alone left that file absent. render_error's continuation
     // line keeps the runtime path's indentation, since the HTML is 
triple-quoted
     // and those spaces reach the browser. chart_df is a copy: the input can 
feed another branch.
-    s"""def render_error(error_msg):
-       |    return '''<h1>Hierarchy chart is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("Hierarchy chart is not available.")}
        |
        |def fail(error_msg):
        |    with open(outputHtml, "w", encoding="utf-8") as output:
@@ -162,9 +160,7 @@ class HierarchyChartOpDesc extends 
PythonVisualizationOpDesc with PlotlyStandalo
        |                         color=$valueLit, hover_data=[$attributes],
        |                         color_continuous_scale='RdBu')
        |        fig.update_layout(margin=dict(l=0, r=0, b=0, t=0))
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("Hierarchy chart saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Hierarchy chart")}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/histogram/HistogramChartOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/histogram/HistogramChartOpDesc.scala
index 2546a514c4..3ccee094f9 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/histogram/HistogramChartOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/histogram/HistogramChartOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.histogram
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{
@@ -134,20 +135,14 @@ class HistogramChartOpDesc extends 
PythonVisualizationOpDesc with PlotlyStandalo
     val patternParam =
       if (pattern.nonEmpty) s""", pattern_shape=${pyStringLiteral(pattern)}""" 
else ""
     val valueLit = pyStringLiteral(value)
-    s"""def render_error(error_msg):
-       |    return '''<h1>Histogram chart is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("Histogram chart is not available.")}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("input table is empty."))
+       |${standaloneErrorPage("input table is empty.")}
        |else:
        |    fig = px.histogram(in1df, x=$valueLit, 
text_auto=True$colorParam$categoryParam$marginalParam$patternParam)
        |    fig.update_layout(margin=dict(l=0, r=0, t=0, b=0))
-       |    fig.write_json(outputJson)
-       |    fig.write_html(outputHtml)
-       |    print("Histogram saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Histogram", indent = 4)}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/histogram2d/Histogram2DOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/histogram2d/Histogram2DOpDesc.scala
index f587a8e504..012194293e 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/histogram2d/Histogram2DOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/histogram2d/Histogram2DOpDesc.scala
@@ -18,6 +18,7 @@
 
 package org.apache.texera.amber.operator.visualization.histogram2d
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaTitle
 import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{
@@ -129,13 +130,11 @@ class Histogram2DOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneC
        |    return f"<h1>2D Histogram failed</h1><p>{msg}</p>"
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("Input table is empty."))
+       |${standaloneErrorPage("Input table is empty.")}
        |else:
        |    chart_df = in1df.dropna(subset=[$xLit, $yLit])
        |    if chart_df.empty:
-       |        with open(outputHtml, "w", encoding="utf-8") as output:
-       |            output.write(render_error("No rows after dropping nulls."))
+       |${standaloneErrorPage("No rows after dropping nulls.", indent = 8)}
        |    else:
        |        fig = px.density_heatmap(
        |            chart_df,
@@ -146,8 +145,6 @@ class Histogram2DOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneC
        |            histnorm='${normalize.getValue}',
        |            text_auto=True
        |        )
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("2D histogram saved to " + outputJson + " and " + 
outputHtml)""".stripMargin
+       |${standaloneFigure("2D histogram", bothOutputs = true)}""".stripMargin
   }
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/lineChart/LineChartOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/lineChart/LineChartOpDesc.scala
index e9178bf66d..23a04d66ad 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/lineChart/LineChartOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/lineChart/LineChartOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.lineChart
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaTitle
 import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{
@@ -152,23 +153,17 @@ class LineChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCod
       .map(line => if (line.isEmpty) line else s"    $line")
       .mkString("\n")
 
-    s"""def render_error(error_msg) -> str:
-       |    return '''<h1>Line chart is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("Line chart is not available.", typed = true)}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("input table is empty."))
+       |${standaloneErrorPage("input table is empty.")}
        |else:
        |    fig = go.Figure()
        |$traces
        |    fig.update_layout(margin=dict(t=0, b=0, l=0, r=0),
        |                      xaxis_title=${pyStringLiteral(xLabel)},
        |                      yaxis_title=${pyStringLiteral(yLabel)})
-       |    fig.write_json(outputJson)
-       |    fig.write_html(outputHtml)
-       |    print("Line chart saved to " + outputJson + " and " + 
outputHtml)""".stripMargin
+       |${standaloneFigure("Line chart", indent = 4, bothOutputs = 
true)}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/nestedTable/NestedTableOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/nestedTable/NestedTableOpDesc.scala
index 878046892c..c3a66b8490 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/nestedTable/NestedTableOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/nestedTable/NestedTableOpDesc.scala
@@ -18,6 +18,7 @@
 
 package org.apache.texera.amber.operator.visualization.nestedTable
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import 
org.apache.texera.amber.pybuilder.PythonTemplateBuilder.PythonTemplateBuilderStringContext
 import org.apache.texera.amber.operator.visualization.PythonVisualizationOpDesc
@@ -71,33 +72,7 @@ class NestedTableOpDesc extends PythonVisualizationOpDesc {
        |
        |        df = pd.DataFrame(data, columns=columns)
        |
-       |        styles = [
-       |            {'selector': 'th', 'props': [('background-color', 
'#f2f2f2'),
-       |                                          ('color', 'black'),
-       |                                          ('font-weight', 'bold'),
-       |                                          ('border', '1px solid #ddd'),
-       |                                          ('padding', '8px'),
-       |                                          ('text-align', 'center')]},
-       |            {'selector': 'td', 'props': [('border', '1px solid #ddd'),
-       |                                          ('padding', '8px'),
-       |                                          ('text-align', 'center')]},
-       |            {'selector': 'caption', 'props': [('caption-side', 'top'),
-       |                                               ('font-size', '16pt'),
-       |                                               ('font-weight', 'bold'),
-       |                                               ('text-align', 'left'),
-       |                                               ('padding', '10px')]},
-       |            {'selector': '.row_heading', 'props': [('text-align', 
'left'),
-       |                                                    ('font-weight', 
'normal')]},
-       |            {'selector': '.blank.level0', 'props': [('display', 
'none')]}
-       |        ]
-       |
-       |        styled_table = (
-       |            df.style
-       |            .set_table_styles(styles)
-       |            .format(precision=2, na_rep="")
-       |            .set_table_attributes('class="dataframe"')
-       |            .hide(axis="index")
-       |        )
+       |${NestedTablePython.body(8)}
        |"""
   }
 
@@ -148,14 +123,10 @@ class NestedTableOpDesc extends PythonVisualizationOpDesc 
{
     s"""import pandas as pd
        |import numpy as np
        |
-       |def render_error(error_msg):
-       |    return '''<h1>Nested Table is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+       |${standaloneError("Nested Table is not available.")}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("input table is empty."))
+       |${standaloneErrorPage("input table is empty.")}
        |else:
        |    columns = pd.MultiIndex.from_tuples([
        |        $multiIndexTuples
@@ -169,33 +140,7 @@ class NestedTableOpDesc extends PythonVisualizationOpDesc {
        |
        |    df = pd.DataFrame(data, columns=columns)
        |
-       |    styles = [
-       |        {'selector': 'th', 'props': [('background-color', '#f2f2f2'),
-       |                                      ('color', 'black'),
-       |                                      ('font-weight', 'bold'),
-       |                                      ('border', '1px solid #ddd'),
-       |                                      ('padding', '8px'),
-       |                                      ('text-align', 'center')]},
-       |        {'selector': 'td', 'props': [('border', '1px solid #ddd'),
-       |                                      ('padding', '8px'),
-       |                                      ('text-align', 'center')]},
-       |        {'selector': 'caption', 'props': [('caption-side', 'top'),
-       |                                           ('font-size', '16pt'),
-       |                                           ('font-weight', 'bold'),
-       |                                           ('text-align', 'left'),
-       |                                           ('padding', '10px')]},
-       |        {'selector': '.row_heading', 'props': [('text-align', 'left'),
-       |                                                ('font-weight', 
'normal')]},
-       |        {'selector': '.blank.level0', 'props': [('display', 'none')]}
-       |    ]
-       |
-       |    styled_table = (
-       |        df.style
-       |        .set_table_styles(styles)
-       |        .format(precision=2, na_rep="")
-       |        .set_table_attributes('class="dataframe"')
-       |        .hide(axis="index")
-       |    )
+       |${NestedTablePython.body(4)}
        |
        |    html = styled_table.to_html()
        |    with open(outputHtml, "w", encoding="utf-8") as output:
@@ -203,3 +148,37 @@ class NestedTableOpDesc extends PythonVisualizationOpDesc {
        |    print("Nested table saved to " + outputHtml)""".stripMargin
   }
 }
+
+private object NestedTablePython {
+  def body(indent: Int): String =
+    org.apache.texera.amber.operator.visualization.PythonCodeFragment.render(
+      """|styles = [
+       |    {'selector': 'th', 'props': [('background-color', '#f2f2f2'),
+       |                                  ('color', 'black'),
+       |                                  ('font-weight', 'bold'),
+       |                                  ('border', '1px solid #ddd'),
+       |                                  ('padding', '8px'),
+       |                                  ('text-align', 'center')]},
+       |    {'selector': 'td', 'props': [('border', '1px solid #ddd'),
+       |                                  ('padding', '8px'),
+       |                                  ('text-align', 'center')]},
+       |    {'selector': 'caption', 'props': [('caption-side', 'top'),
+       |                                       ('font-size', '16pt'),
+       |                                       ('font-weight', 'bold'),
+       |                                       ('text-align', 'left'),
+       |                                       ('padding', '10px')]},
+       |    {'selector': '.row_heading', 'props': [('text-align', 'left'),
+       |                                            ('font-weight', 
'normal')]},
+       |    {'selector': '.blank.level0', 'props': [('display', 'none')]}
+       |]
+       |
+       |styled_table = (
+       |    df.style
+       |    .set_table_styles(styles)
+       |    .format(precision=2, na_rep="")
+       |    .set_table_attributes('class="dataframe"')
+       |    .hide(axis="index")
+       |)""",
+      indent
+    )
+}
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/networkGraph/NetworkGraphOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/networkGraph/NetworkGraphOpDesc.scala
index 23abd3a9b0..ebace5c7a3 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/networkGraph/NetworkGraphOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/networkGraph/NetworkGraphOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.networkGraph
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaTitle
 import 
org.apache.texera.amber.pybuilder.PythonTemplateBuilder.PythonTemplateBuilderStringContext
@@ -204,19 +205,14 @@ class NetworkGraphOpDesc extends 
PythonVisualizationOpDesc with PlotlyStandalone
     val titleLit = pyStringLiteral(s"<br>$title")
     s"""import networkx as nx
        |
-       |def render_error(error_msg):
-       |    return '''<h1>Network graph is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+       |${standaloneError("Network graph is not available.")}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("Table should not have any 
empty/null values or fields."))
+       |${standaloneErrorPage("Table should not have any empty/null values or 
fields.")}
        |else:
        |    table = 
in1df.dropna(subset=[$sourceLit]).dropna(subset=[$destinationLit]).copy()
        |    if table.empty:
-       |        with open(outputHtml, "w", encoding="utf-8") as output:
-       |            output.write(render_error("Table should not have any 
empty/null values or fields."))
+       |${standaloneErrorPage("Table should not have any empty/null values or 
fields.", indent = 8)}
        |    else:
        |        sources = table[$sourceLit]
        |        destinations = table[$destinationLit]
@@ -306,9 +302,7 @@ class NetworkGraphOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandalone
        |                itemdoubleclick=False
        |            )
        |        )
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("Network graph saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Network graph")}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/parallelCoordinatesPlot/ParallelCoordinatesPlotOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/parallelCoordinatesPlot/ParallelCoordinatesPlotOpDesc.scala
index 58347b3867..3b63d7e967 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/parallelCoordinatesPlot/ParallelCoordinatesPlotOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/parallelCoordinatesPlot/ParallelCoordinatesPlotOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.parallelCoordinatesPlot
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import org.apache.texera.amber.operator.visualization.PlotlyStandaloneCode
@@ -137,27 +138,20 @@ class ParallelCoordinatesPlotOpDesc extends 
PythonVisualizationOpDesc with Plotl
     val colorArg =
       if (color != null && color.nonEmpty) s""", color=$colorLit""" else ""
 
-    s"""def render_error(error_msg):
-       |    return '''<h1>Parallel coordinates plot is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("Parallel coordinates plot is not available.")}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("Input table is empty."))
+       |${standaloneErrorPage("Input table is empty.")}
        |else:
        |    table = 
in1df[in1df[$dimCols].notnull().all(axis=1)$colorFilter].copy()
        |    if table.empty:
-       |        with open(outputHtml, "w", encoding="utf-8") as output:
-       |            output.write(render_error("No valid rows after 
filtering."))
+       |${standaloneErrorPage("No valid rows after filtering.", indent = 8)}
        |    else:
        |        fig = px.parallel_coordinates(
        |            table,
        |            dimensions=$dimCols$colorArg
        |        )
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("Parallel coordinates plot saved to " + 
outputHtml)""".stripMargin
+       |${standaloneFigure("Parallel coordinates plot")}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/pieChart/PieChartOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/pieChart/PieChartOpDesc.scala
index 00c942584d..ac4197db9b 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/pieChart/PieChartOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/pieChart/PieChartOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.pieChart
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{
@@ -126,29 +127,21 @@ class PieChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCode
   override def generateStandaloneCode(): String = {
     val nameLit = pyStringLiteral(name)
     val valueLit = pyStringLiteral(value)
-    s"""def render_error(error_msg):
-       |    return '''<h1>PieChart is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("PieChart is not available.")}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("input table is empty."))
+       |${standaloneErrorPage("input table is empty.")}
        |else:
        |    table = in1df.dropna(subset=[$valueLit, $nameLit])
        |    if table.empty:
-       |        with open(outputHtml, "w", encoding="utf-8") as output:
-       |            output.write(render_error("value column contains only 
non-positive numbers."))
+       |${standaloneErrorPage("value column contains only non-positive 
numbers.", indent = 8)}
        |    elif table.duplicated(subset=[$nameLit]).any():
-       |        with open(outputHtml, "w", encoding="utf-8") as output:
-       |            output.write(render_error("duplicates in name column, need 
to aggregate"))
+       |${standaloneErrorPage("duplicates in name column, need to aggregate", 
indent = 8)}
        |    else:
        |        fig = px.pie(table, names=$nameLit, values=$valueLit)
        |        fig.update_traces(textposition='inside', 
textinfo='percent+label')
        |        fig.update_layout(margin=dict(t=0, b=0, l=0, r=0))
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("Pie chart saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Pie chart")}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/polarChart/PolarChartOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/polarChart/PolarChartOpDesc.scala
index 4c023c6dbf..c4a28486f1 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/polarChart/PolarChartOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/polarChart/PolarChartOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.polarChart
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import org.apache.texera.amber.core.workflow.OutputPort.OutputMode
@@ -147,9 +148,7 @@ class PolarChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCo
        |        marker=dict(size=10, opacity=0.7, line=dict(color='white'))
        |    ))
        |    fig.update_layout(title='Polar Chart', showlegend=False)
-       |    fig.write_json(outputJson)
-       |    fig.write_html(outputHtml)
-       |    print("Polar chart saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Polar chart", indent = 4)}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/quiverPlot/QuiverPlotOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/quiverPlot/QuiverPlotOpDesc.scala
index 0147c5b932..b2380f389b 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/quiverPlot/QuiverPlotOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/quiverPlot/QuiverPlotOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.quiverPlot
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import 
org.apache.texera.amber.pybuilder.PythonTemplateBuilder.PythonTemplateBuilderStringContext
@@ -159,14 +160,10 @@ class QuiverPlotOpDesc extends PythonVisualizationOpDesc {
     val vLit = pyStringLiteral(v)
     s"""import plotly.figure_factory as ff
        |
-       |def render_error(error_msg):
-       |    return '''<h1>Quiver Plot is not available.</h1>
-       |                  <p>Reasons are: {} </p>
-       |               '''.format(error_msg)
+       |${standaloneError("Quiver Plot is not available.", plural = true)}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("Input table is empty."))
+       |${standaloneErrorPage("Input table is empty.")}
        |else:
        |    table = in1df
        |    required_columns = {$xLit, $yLit, $uLit, $vLit}
@@ -187,9 +184,7 @@ class QuiverPlotOpDesc extends PythonVisualizationOpDesc {
        |                    table[$uLit], table[$vLit],
        |                    scale=0.1
        |                )
-       |                fig.write_json(outputJson)
-       |                fig.write_html(outputHtml)
-       |                print("Quiver plot saved to " + outputHtml)
+       |${standaloneFigure("Quiver plot", indent = 16)}
        |            except Exception as e:
        |                with open(outputHtml, "w", encoding="utf-8") as output:
        |                    output.write(render_error(f"Plotly error: 
{str(e)}"))""".stripMargin
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/radarChart/RadarChartOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/radarChart/RadarChartOpDesc.scala
index e964e6b782..6e81b33255 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/radarChart/RadarChartOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/radarChart/RadarChartOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.radarChart
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import org.apache.texera.amber.operator.visualization.PlotlyStandaloneCode
@@ -162,14 +163,10 @@ class RadarChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCo
     val requiredCols =
       (Seq(pyStringLiteral(nameColumn)) ++ valueColumns.map(pyStringLiteral))
         .mkString("[", ", ", "]")
-    s"""def render_error(error_msg):
-       |    return '''<h1>RadarChart is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("RadarChart is not available.")}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("input table is empty."))
+       |${standaloneErrorPage("input table is empty.")}
        |else:
        |    table = in1df.copy()
        |    required_cols = $requiredCols
@@ -179,8 +176,7 @@ class RadarChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCo
        |        table[col] = pd.to_numeric(table[col], errors='coerce')
        |    table.dropna(subset=value_cols, inplace=True)
        |    if table.empty:
-       |        with open(outputHtml, "w", encoding="utf-8") as output:
-       |            output.write(render_error("input table is empty after 
removing missing values."))
+       |${standaloneErrorPage("input table is empty after removing missing 
values.", indent = 8)}
        |    else:
        |        fig = go.Figure()
        |        categories = $valueColsList
@@ -205,9 +201,7 @@ class RadarChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCo
        |            showlegend=True,
        |            margin=dict(t=40, b=40, l=40, r=40)
        |        )
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("Radar chart saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Radar chart")}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/radarPlot/RadarPlotOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/radarPlot/RadarPlotOpDesc.scala
index ae2a827895..3ff89e666b 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/radarPlot/RadarPlotOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/radarPlot/RadarPlotOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.radarPlot
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import org.apache.texera.amber.operator.metadata.annotations.{
@@ -136,63 +137,7 @@ class RadarPlotOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCod
        |        show_markers = ${toPythonBool(showMarkers)}
        |        show_legend = ${toPythonBool(showLegend)}
        |
-       |        selected_table_df = table[categories].astype(float)
-       |        selected_table = selected_table_df.values
-       |
-       |        trace_names = (
-       |            table[trace_name_col].values if trace_name_col
-       |            else np.full(len(table), "", dtype=object)
-       |        )
-       |
-       |        trace_colors = [None] * len(table)
-       |        if trace_color_col:
-       |            unique_vals = table[trace_color_col].unique()
-       |            color_map = {val: px.colors.qualitative.Plotly[idx % 
len(px.colors.qualitative.Plotly)]
-       |                         for idx, val in enumerate(unique_vals)}
-       |            nan_color = '#000000'
-       |            trace_colors = 
table[trace_color_col].map(color_map).fillna(nan_color).values
-       |
-       |        hover_texts = []
-       |        for idx, row in enumerate(selected_table):
-       |            name_prefix = str(trace_names[idx]) + "<br>" if 
trace_names[idx] else ""
-       |            row_hover_texts = []
-       |            for attr, value in zip(categories, row):
-       |                row_hover_texts.append(name_prefix + attr + ": " + 
str(value))
-       |            hover_texts.append(row_hover_texts)
-       |
-       |        if max_normalize:
-       |            max_vals = selected_table_df.max().values
-       |            max_vals[max_vals == 0] = 1
-       |            selected_table = selected_table / max_vals
-       |
-       |        selected_table = np.nan_to_num(selected_table)
-       |
-       |        fig = go.Figure()
-       |
-       |        for idx, row in enumerate(selected_table):
-       |            # To connect ensure all points in the radar trace are 
connected
-       |            closed_row = row.tolist() + [row[0]]
-       |            closed_categories = categories + [categories[0]]
-       |            closed_hover_texts = hover_texts[idx] + 
[hover_texts[idx][0]]
-       |
-       |            fig.add_trace(go.Scatterpolar(
-       |                r=closed_row,
-       |                theta=closed_categories,
-       |                fill='toself' if fill_trace else 'none',
-       |                name=str(trace_names[idx]) if trace_names[idx] else "",
-       |                text=closed_hover_texts,
-       |                hoverinfo="text",
-       |                mode="lines+markers" if show_markers else "lines",
-       |                line=dict(dash=line_pattern, color=trace_colors[idx] 
if trace_colors[idx] else None),
-       |                marker=dict(color=trace_colors[idx]) if 
trace_colors[idx] else {}
-       |            ))
-       |
-       |        fig.update_layout(
-       |            polar=dict(radialaxis=dict(visible=True)),
-       |            showlegend=show_legend,
-       |            width=600,
-       |            height=600
-       |        )
+       |${RadarPlotPython.body(8)}
        |"""
   }
 
@@ -241,19 +186,14 @@ class RadarPlotOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCod
     // HTML is triple-quoted, so those spaces reach the browser.
     s"""import numpy as np
        |
-       |def render_error(error_msg):
-       |    return '''<h1>Radar Plot is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+       |${standaloneError("Radar Plot is not available.")}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("Input table is empty."))
+       |${standaloneErrorPage("Input table is empty.")}
        |else:
        |    categories = [$attrList]
        |    if not categories:
-       |        with open(outputHtml, "w", encoding="utf-8") as output:
-       |            output.write(render_error("No columns selected as axes."))
+       |${standaloneErrorPage("No columns selected as axes.", indent = 8)}
        |    else:
        |        table = in1df
        |        trace_name_col = $traceNameCol
@@ -264,64 +204,71 @@ class RadarPlotOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCod
        |        show_markers = ${toPythonBool(showMarkers)}
        |        show_legend = ${toPythonBool(showLegend)}
        |
-       |        selected_table_df = table[categories].astype(float)
-       |        selected_table = selected_table_df.values
+       |${RadarPlotPython.body(8)}
+       |${standaloneFigure("Radar plot")}""".stripMargin
+  }
+}
+
+private object RadarPlotPython {
+  def body(indent: Int): String =
+    org.apache.texera.amber.operator.visualization.PythonCodeFragment.render(
+      """|selected_table_df = table[categories].astype(float)
+       |selected_table = selected_table_df.values
        |
-       |        trace_names = (
-       |            table[trace_name_col].values if trace_name_col
-       |            else np.full(len(table), "", dtype=object)
-       |        )
+       |trace_names = (
+       |    table[trace_name_col].values if trace_name_col
+       |    else np.full(len(table), "", dtype=object)
+       |)
        |
-       |        trace_colors = [None] * len(table)
-       |        if trace_color_col:
-       |            unique_vals = table[trace_color_col].unique()
-       |            color_map = {val: px.colors.qualitative.Plotly[idx % 
len(px.colors.qualitative.Plotly)]
-       |                         for idx, val in enumerate(unique_vals)}
-       |            nan_color = '#000000'
-       |            trace_colors = 
table[trace_color_col].map(color_map).fillna(nan_color).values
+       |trace_colors = [None] * len(table)
+       |if trace_color_col:
+       |    unique_vals = table[trace_color_col].unique()
+       |    color_map = {val: px.colors.qualitative.Plotly[idx % 
len(px.colors.qualitative.Plotly)]
+       |                 for idx, val in enumerate(unique_vals)}
+       |    nan_color = '#000000'
+       |    trace_colors = 
table[trace_color_col].map(color_map).fillna(nan_color).values
        |
-       |        hover_texts = []
-       |        for idx, row in enumerate(selected_table):
-       |            name_prefix = str(trace_names[idx]) + "<br>" if 
trace_names[idx] else ""
-       |            row_hover_texts = []
-       |            for attr, value in zip(categories, row):
-       |                row_hover_texts.append(name_prefix + attr + ": " + 
str(value))
-       |            hover_texts.append(row_hover_texts)
+       |hover_texts = []
+       |for idx, row in enumerate(selected_table):
+       |    name_prefix = str(trace_names[idx]) + "<br>" if trace_names[idx] 
else ""
+       |    row_hover_texts = []
+       |    for attr, value in zip(categories, row):
+       |        row_hover_texts.append(name_prefix + attr + ": " + str(value))
+       |    hover_texts.append(row_hover_texts)
        |
-       |        if max_normalize:
-       |            max_vals = selected_table_df.max().values
-       |            max_vals[max_vals == 0] = 1
-       |            selected_table = selected_table / max_vals
+       |if max_normalize:
+       |    max_vals = selected_table_df.max().values
+       |    max_vals[max_vals == 0] = 1
+       |    selected_table = selected_table / max_vals
        |
-       |        selected_table = np.nan_to_num(selected_table)
+       |selected_table = np.nan_to_num(selected_table)
        |
-       |        fig = go.Figure()
+       |fig = go.Figure()
        |
-       |        for idx, row in enumerate(selected_table):
-       |            closed_row = row.tolist() + [row[0]]
-       |            closed_categories = categories + [categories[0]]
-       |            closed_hover_texts = hover_texts[idx] + 
[hover_texts[idx][0]]
+       |for idx, row in enumerate(selected_table):
+       |    # To connect ensure all points in the radar trace are connected
+       |    closed_row = row.tolist() + [row[0]]
+       |    closed_categories = categories + [categories[0]]
+       |    closed_hover_texts = hover_texts[idx] + [hover_texts[idx][0]]
        |
-       |            fig.add_trace(go.Scatterpolar(
-       |                r=closed_row,
-       |                theta=closed_categories,
-       |                fill='toself' if fill_trace else 'none',
-       |                name=str(trace_names[idx]) if trace_names[idx] else "",
-       |                text=closed_hover_texts,
-       |                hoverinfo="text",
-       |                mode="lines+markers" if show_markers else "lines",
-       |                line=dict(dash=line_pattern, color=trace_colors[idx] 
if trace_colors[idx] else None),
-       |                marker=dict(color=trace_colors[idx]) if 
trace_colors[idx] else {}
-       |            ))
+       |    fig.add_trace(go.Scatterpolar(
+       |        r=closed_row,
+       |        theta=closed_categories,
+       |        fill='toself' if fill_trace else 'none',
+       |        name=str(trace_names[idx]) if trace_names[idx] else "",
+       |        text=closed_hover_texts,
+       |        hoverinfo="text",
+       |        mode="lines+markers" if show_markers else "lines",
+       |        line=dict(dash=line_pattern, color=trace_colors[idx] if 
trace_colors[idx] else None),
+       |        marker=dict(color=trace_colors[idx]) if trace_colors[idx] else 
{}
+       |    ))
        |
-       |        fig.update_layout(
-       |            polar=dict(radialaxis=dict(visible=True)),
-       |            showlegend=show_legend,
-       |            width=600,
-       |            height=600
-       |        )
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("Radar plot saved to " + outputHtml)""".stripMargin
-  }
+       |fig.update_layout(
+       |    polar=dict(radialaxis=dict(visible=True)),
+       |    showlegend=show_legend,
+       |    width=600,
+       |    height=600
+       |)""",
+      indent
+    )
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/rangeSlider/RangeSliderOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/rangeSlider/RangeSliderOpDesc.scala
index cf96fa725a..7deac358d4 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/rangeSlider/RangeSliderOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/rangeSlider/RangeSliderOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.rangeSlider
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import 
org.apache.texera.amber.pybuilder.PythonTemplateBuilder.PythonTemplateBuilderStringContext
@@ -139,17 +140,12 @@ class RangeSliderOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneC
     val functionType = duplicateType.getFunctionType
     val xAxisLit = pyStringLiteral(xAxis)
     val yAxisLit = pyStringLiteral(yAxis)
-    s"""def render_error(error_msg):
-       |    return '''<h1>RangeChart is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("RangeChart is not available.")}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("input table is empty."))
+       |${standaloneErrorPage("input table is empty.")}
        |elif $yAxisLit.strip() == "" or $xAxisLit.strip() == "":
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("Y-axis or X-axis is empty"))
+       |${standaloneErrorPage("Y-axis or X-axis is empty")}
        |else:
        |    table = in1df
        |    table = table.dropna(subset=[$xAxisLit, $yAxisLit])
@@ -169,9 +165,7 @@ class RangeSliderOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneC
        |            )
        |        )
        |    )
-       |    fig.write_json(outputJson)
-       |    fig.write_html(outputHtml)
-       |    print("Range slider saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Range slider", indent = 4)}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/sankeyDiagram/SankeyDiagramOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/sankeyDiagram/SankeyDiagramOpDesc.scala
index dc9e2cce01..65798707fd 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/sankeyDiagram/SankeyDiagramOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/sankeyDiagram/SankeyDiagramOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.sankeyDiagram
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import 
org.apache.texera.amber.pybuilder.PythonTemplateBuilder.PythonTemplateBuilderStringContext
@@ -143,19 +144,17 @@ class SankeyDiagramOpDesc extends 
PythonVisualizationOpDesc with PlotlyStandalon
     val sourceLit = pyStringLiteral(sourceAttribute)
     val targetLit = pyStringLiteral(targetAttribute)
     val valueLit = pyStringLiteral(valueAttribute)
-    s"""def render_error(error_msg):
-       |    return '''<h1>Sankey Diagram is not available.</h1>
-       |                  <p>Reasons are: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("Sankey Diagram is not available.", plural = true)}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("Input table is empty."))
+       |${standaloneErrorPage("Input table is empty.")}
        |else:
        |    table = in1df.groupby([$sourceLit, 
$targetLit])[$valueLit].sum().reset_index(name="value")
        |    if table.empty:
-       |        with open(outputHtml, "w", encoding="utf-8") as output:
-       |            output.write(render_error("No valid rows left (every row 
has at least 1 missing value)."))
+       |${standaloneErrorPage(
+      "No valid rows left (every row has at least 1 missing value).",
+      indent = 8
+    )}
        |    else:
        |        labels = pd.concat([table[$sourceLit], 
table[$targetLit]]).unique().tolist()
        |        table["source_index"] = table[$sourceLit].apply(lambda x: 
labels.index(x))
@@ -175,9 +174,7 @@ class SankeyDiagramOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandalon
        |            )
        |        )])
        |        fig.update_layout(title_text="Sankey Diagram", font_size=10)
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("Sankey diagram saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Sankey diagram")}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/scatter3DChart/Scatter3dChartOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/scatter3DChart/Scatter3dChartOpDesc.scala
index 89f643815e..c07ca12755 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/scatter3DChart/Scatter3dChartOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/scatter3DChart/Scatter3dChartOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.scatter3DChart
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaTitle
 import 
org.apache.texera.amber.pybuilder.PythonTemplateBuilder.PythonTemplateBuilderStringContext
@@ -123,14 +124,10 @@ class Scatter3dChartOpDesc extends 
PythonVisualizationOpDesc with PlotlyStandalo
     val xLit = pyStringLiteral(x)
     val yLit = pyStringLiteral(y)
     val zLit = pyStringLiteral(z)
-    s"""def render_error(error_msg):
-       |    return '''<h1>Chart is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("Chart is not available.")}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("input table is empty."))
+       |${standaloneErrorPage("input table is empty.")}
        |else:
        |    table = in1df
        |    fig = go.Figure(data=[go.Scatter3d(
@@ -153,9 +150,7 @@ class Scatter3dChartOpDesc extends 
PythonVisualizationOpDesc with PlotlyStandalo
        |        ),
        |        margin=dict(t=0, b=0, l=0, r=0)
        |    )
-       |    fig.write_json(outputJson)
-       |    fig.write_html(outputHtml)
-       |    print("Scatter3D chart saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Scatter3D chart", indent = 4)}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/scatterplot/ScatterplotOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/scatterplot/ScatterplotOpDesc.scala
index b5358b4f4b..cd07ae535a 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/scatterplot/ScatterplotOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/scatterplot/ScatterplotOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.scatterplot
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import 
org.apache.texera.amber.pybuilder.PythonTemplateBuilder.PythonTemplateBuilderStringContext
@@ -183,25 +184,21 @@ class ScatterplotOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneC
     if (yLogScale) args += "log_y=True"
     if (hoverName.nonEmpty) args += 
s"""hover_name=${pyStringLiteral(hoverName)}"""
 
-    s"""def render_error(error_msg):
-       |    return '''<h1>Scatter Plot is not available.</h1>
-       |                  <p>Reasons are: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("Scatter Plot is not available.", plural = true)}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("Input table is empty."))
+       |${standaloneErrorPage("Input table is empty.")}
        |else:
        |    table = in1df.dropna(subset=$dropCols).copy()
        |    if table.empty:
-       |        with open(outputHtml, "w", encoding="utf-8") as output:
-       |            output.write(render_error("No valid rows left (every row 
has at least 1 missing value)."))
+       |${standaloneErrorPage(
+      "No valid rows left (every row has at least 1 missing value).",
+      indent = 8
+    )}
        |    else:
        |        fig = go.Figure(px.scatter(table, ${args.mkString(", ")}))
        |        fig.update_layout(margin=dict(l=0, r=0, t=0, b=0))
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("Scatter plot saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Scatter plot")}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/stripChart/StripChartOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/stripChart/StripChartOpDesc.scala
index 9d38910e2a..9bb965ca79 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/stripChart/StripChartOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/stripChart/StripChartOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.stripChart
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaTitle
 import 
org.apache.texera.amber.pybuilder.PythonTemplateBuilder.PythonTemplateBuilderStringContext
@@ -138,9 +139,7 @@ class StripChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCo
        |    yaxis_title=$yLit,
        |    hovermode='closest'
        |)
-       |fig.write_json(outputJson)
-       |fig.write_html(outputHtml)
-       |print("Strip chart saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Strip chart", indent = 0)}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/tablesChart/TablesPlotOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/tablesChart/TablesPlotOpDesc.scala
index d3710dfe34..2d36d8b6cb 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/tablesChart/TablesPlotOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/tablesChart/TablesPlotOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.tablesChart
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import 
org.apache.texera.amber.pybuilder.PythonTemplateBuilder.PythonTemplateBuilderStringContext
 import org.apache.texera.amber.operator.visualization.PlotlyStandaloneCode
@@ -119,13 +120,14 @@ class TablesPlotOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCo
        |
        |attributes = $columnsList
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("input table is empty."))
+       |${standaloneErrorPage("input table is empty.")}
        |else:
        |    table = in1df.dropna(subset=attributes)
        |    if table.empty:
-       |        with open(outputHtml, "w", encoding="utf-8") as output:
-       |            output.write(render_error("value column contains only 
non-positive numbers or nulls."))
+       |${standaloneErrorPage(
+      "value column contains only non-positive numbers or nulls.",
+      indent = 8
+    )}
        |    else:
        |        filtered_table = table[attributes]
        |        headers = filtered_table.columns.tolist()
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ternaryContour/TernaryContourOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ternaryContour/TernaryContourOpDesc.scala
index 71f691d6f1..d9da28438f 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ternaryContour/TernaryContourOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ternaryContour/TernaryContourOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.ternaryContour
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import org.apache.texera.amber.core.workflow.OutputPort.OutputMode
@@ -176,14 +177,10 @@ class TernaryContourOpDesc extends 
PythonVisualizationOpDesc {
     s"""import plotly.figure_factory as ff
        |import numpy as np
        |
-       |def render_error(error_msg):
-       |    return '''<h1>TernaryContour is not available.</h1>
-       |                  <p>Reasons are: {} </p>
-       |               '''.format(error_msg)
+       |${standaloneError("TernaryContour is not available.", plural = true)}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("Input table is empty."))
+       |${standaloneErrorPage("Input table is empty.")}
        |else:
        |    table = in1df.copy()
        |    table.dropna(subset=[$firstLit, $secondLit, $thirdLit, 
$fourthLit], inplace=True)
@@ -191,8 +188,10 @@ class TernaryContourOpDesc extends 
PythonVisualizationOpDesc {
        |    s = table[$firstLit] + table[$secondLit] + table[$thirdLit]
        |    table = table[s > 0]
        |    if table.empty:
-       |        with open(outputHtml, "w", encoding="utf-8") as output:
-       |            output.write(render_error("No valid rows left (every row 
has at least 1 missing value)."))
+       |${standaloneErrorPage(
+      "No valid rows left (every row has at least 1 missing value).",
+      indent = 8
+    )}
        |    else:
        |        A = table[$firstLit].to_numpy()
        |        B = table[$secondLit].to_numpy()
@@ -204,9 +203,7 @@ class TernaryContourOpDesc extends 
PythonVisualizationOpDesc {
        |            pole_labels=[$firstLit, $secondLit, $thirdLit],
        |            interp_mode='cartesian'
        |        )
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("Ternary contour saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Ternary contour")}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ternaryPlot/TernaryPlotOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ternaryPlot/TernaryPlotOpDesc.scala
index 14ec74c334..f3347147f2 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ternaryPlot/TernaryPlotOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ternaryPlot/TernaryPlotOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.ternaryPlot
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import 
org.apache.texera.amber.pybuilder.PythonTemplateBuilder.PythonTemplateBuilderStringContext
@@ -163,24 +164,20 @@ class TernaryPlotOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneC
     val firstLit = pyStringLiteral(firstVariable)
     val secondLit = pyStringLiteral(secondVariable)
     val thirdLit = pyStringLiteral(thirdVariable)
-    s"""def render_error(error_msg):
-       |    return '''<h1>TernaryPlot is not available.</h1>
-       |                  <p>Reasons are: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("TernaryPlot is not available.", plural = true)}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("Input table is empty."))
+       |${standaloneErrorPage("Input table is empty.")}
        |else:
        |    table = in1df.dropna(subset=[$firstLit, $secondLit, 
$thirdLit]).copy()
        |    if table.empty:
-       |        with open(outputHtml, "w", encoding="utf-8") as output:
-       |            output.write(render_error("No valid rows left (every row 
has at least 1 missing value)."))
+       |${standaloneErrorPage(
+      "No valid rows left (every row has at least 1 missing value).",
+      indent = 8
+    )}
        |    else:
        |        fig = px.scatter_ternary(table, a=$firstLit, b=$secondLit, 
c=$thirdLit$colorArg)
-       |        fig.write_json(outputJson)
-       |        fig.write_html(outputHtml)
-       |        print("Ternary plot saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Ternary plot")}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/timeSeriesplot/TimeSeriesOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/timeSeriesplot/TimeSeriesOpDesc.scala
index a7ae7636d1..b350c9544b 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/timeSeriesplot/TimeSeriesOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/timeSeriesplot/TimeSeriesOpDesc.scala
@@ -18,6 +18,7 @@
  */
 package org.apache.texera.amber.operator.visualization.timeSeriesplot
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import 
org.apache.texera.amber.pybuilder.PythonTemplateBuilder.PythonTemplateBuilderStringContext
@@ -175,16 +176,14 @@ class TimeSeriesOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCo
        |    return f"<h1>Time Series Plot is not available.</h1><p>Reason: 
{msg}</p>"
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("Input table is empty."))
+       |${standaloneErrorPage("Input table is empty.")}
        |else:
        |    try:
        |        table = in1df.copy()
        |        table[$timeLit] = pd.to_datetime(table[$timeLit], 
errors='coerce')
        |        table = 
table.dropna(subset=$dropnaStr).sort_values(by=$timeLit)
        |        if table.empty:
-       |            with open(outputHtml, "w", encoding="utf-8") as output:
-       |                output.write(render_error("Table became empty after 
filtering."))
+       |${standaloneErrorPage("Table became empty after filtering.", indent = 
12)}
        |        else:
        |            fig = $plotFunc(table, x=$timeLit, 
y=$valueLit$colorArg$facetArg)
        |            if $showSlider:
@@ -196,9 +195,7 @@ class TimeSeriesOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCo
        |                yaxis_title=$valueLit,
        |                template="plotly_white"
        |            )
-       |            fig.write_json(outputJson)
-       |            fig.write_html(outputHtml)
-       |            print("Time series plot saved to " + outputHtml)
+       |${standaloneFigure("Time series plot", indent = 12)}
        |    except Exception as e:
        |        with open(outputHtml, "w", encoding="utf-8") as output:
        |            output.write(render_error(str(e)))""".stripMargin
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/treeplot/TreePlotOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/treeplot/TreePlotOpDesc.scala
index d3f11d90f2..7d66be0382 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/treeplot/TreePlotOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/treeplot/TreePlotOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.treeplot
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaTitle
 import 
org.apache.texera.amber.pybuilder.PythonTemplateBuilder.PythonTemplateBuilderStringContext
@@ -99,64 +100,7 @@ class TreePlotOpDesc extends PythonVisualizationOpDesc with 
PlotlyStandaloneCode
        |        return annotations
        |
        |    def build_tree_layout(self, edges):
-       |        # Tidy top-down tree: depth picks the row, a leaf takes the 
next
-       |        # free column and a parent sits centred over its own children.
-       |        labels = []
-       |        known = set()
-       |        for parent, child in edges:
-       |            for node in (parent, child):
-       |                if node not in known:
-       |                    known.add(node)
-       |                    labels.append(node)
-       |
-       |        children = {label: [] for label in labels}
-       |        has_parent = set()
-       |        seen = set()
-       |        for parent, child in edges:
-       |            if (parent, child) not in seen:
-       |                seen.add((parent, child))
-       |                children[parent].append(child)
-       |            has_parent.add(child)
-       |
-       |        depth = {}
-       |        column = {}
-       |        claimed = {}
-       |        placed = set()
-       |        next_column = 0
-       |
-       |        def grow(root):
-       |            nonlocal next_column
-       |            placed.add(root)
-       |            stack = [(root, 0, False)]
-       |            while stack:
-       |                node, level, folded = stack.pop()
-       |                if folded:
-       |                    kids = claimed[node]
-       |                    if kids:
-       |                        column[node] = sum(column[kid] for kid in 
kids) / len(kids)
-       |                    else:
-       |                        column[node] = next_column
-       |                        next_column += 1
-       |                    continue
-       |                depth[node] = level
-       |                # A node belongs to whichever parent reaches it first, 
so a
-       |                # cycle or a shared child is never laid out twice.
-       |                kids = [kid for kid in children[node] if kid not in 
placed]
-       |                placed.update(kids)
-       |                claimed[node] = kids
-       |                stack.append((node, level, True))
-       |                for kid in reversed(kids):
-       |                    stack.append((kid, level + 1, False))
-       |
-       |        for label in labels:
-       |            if label not in placed and label not in has_parent:
-       |                grow(label)
-       |        # Whatever is left sits in a cycle that no root can reach.
-       |        for label in labels:
-       |            if label not in placed:
-       |                grow(label)
-       |        # The y-axis is inverted here so the tree grows top-down.
-       |        return labels, [(column[label], -depth[label]) for label in 
labels]
+       |${TreePlotPython.body(8)}
        |
        |    @overrides
        |    def process_table(self, table: Table, port: int) -> 
Iterator[Optional[TableLike]]:
@@ -273,58 +217,7 @@ class TreePlotOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCode
        |    return annotations
        |
        |def build_tree_layout(edges):
-       |    labels = []
-       |    known = set()
-       |    for parent, child in edges:
-       |        for node in (parent, child):
-       |            if node not in known:
-       |                known.add(node)
-       |                labels.append(node)
-       |
-       |    children = {label: [] for label in labels}
-       |    has_parent = set()
-       |    seen = set()
-       |    for parent, child in edges:
-       |        if (parent, child) not in seen:
-       |            seen.add((parent, child))
-       |            children[parent].append(child)
-       |        has_parent.add(child)
-       |
-       |    depth = {}
-       |    column = {}
-       |    claimed = {}
-       |    placed = set()
-       |    next_column = 0
-       |
-       |    def grow(root):
-       |        nonlocal next_column
-       |        placed.add(root)
-       |        stack = [(root, 0, False)]
-       |        while stack:
-       |            node, level, folded = stack.pop()
-       |            if folded:
-       |                kids = claimed[node]
-       |                if kids:
-       |                    column[node] = sum(column[kid] for kid in kids) / 
len(kids)
-       |                else:
-       |                    column[node] = next_column
-       |                    next_column += 1
-       |                continue
-       |            depth[node] = level
-       |            kids = [kid for kid in children[node] if kid not in placed]
-       |            placed.update(kids)
-       |            claimed[node] = kids
-       |            stack.append((node, level, True))
-       |            for kid in reversed(kids):
-       |                stack.append((kid, level + 1, False))
-       |
-       |    for label in labels:
-       |        if label not in placed and label not in has_parent:
-       |            grow(label)
-       |    for label in labels:
-       |        if label not in placed:
-       |            grow(label)
-       |    return labels, [(column[label], -depth[label]) for label in labels]
+       |${TreePlotPython.body(4)}
        |
        |def compute_tree_layout(edges):
        |    try:
@@ -334,8 +227,7 @@ class TreePlotOpDesc extends PythonVisualizationOpDesc with 
PlotlyStandaloneCode
        |    return {labels[index]: coords[index] for index in 
range(len(labels))}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("Input table is empty."))
+       |${standaloneErrorPage("Input table is empty.")}
        |else:
        |    edges = []
        |    for item in in1df[${pyStringLiteral(edgeListColumn)}].dropna():
@@ -394,12 +286,75 @@ class TreePlotOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneCode
        |                              dragmode='pan',
        |                              hovermode='closest',
        |                              plot_bgcolor='rgb(248,248,248)')
-       |            fig.write_json(outputJson)
-       |            fig.write_html(outputHtml)
-       |            print("Tree plot saved to " + outputHtml)
+       |${standaloneFigure("Tree plot", indent = 12)}
        |        except TreeLayoutError as e:
        |            with open(outputHtml, "w", encoding="utf-8") as output:
        |                output.write(render_error(str(e)))""".stripMargin
   }
 
 }
+
+private object TreePlotPython {
+  def body(indent: Int): String =
+    org.apache.texera.amber.operator.visualization.PythonCodeFragment.render(
+      """|# Tidy top-down tree: depth picks the row, a leaf takes the next
+       |# free column and a parent sits centred over its own children.
+       |labels = []
+       |known = set()
+       |for parent, child in edges:
+       |    for node in (parent, child):
+       |        if node not in known:
+       |            known.add(node)
+       |            labels.append(node)
+       |
+       |children = {label: [] for label in labels}
+       |has_parent = set()
+       |seen = set()
+       |for parent, child in edges:
+       |    if (parent, child) not in seen:
+       |        seen.add((parent, child))
+       |        children[parent].append(child)
+       |    has_parent.add(child)
+       |
+       |depth = {}
+       |column = {}
+       |claimed = {}
+       |placed = set()
+       |next_column = 0
+       |
+       |def grow(root):
+       |    nonlocal next_column
+       |    placed.add(root)
+       |    stack = [(root, 0, False)]
+       |    while stack:
+       |        node, level, folded = stack.pop()
+       |        if folded:
+       |            kids = claimed[node]
+       |            if kids:
+       |                column[node] = sum(column[kid] for kid in kids) / 
len(kids)
+       |            else:
+       |                column[node] = next_column
+       |                next_column += 1
+       |            continue
+       |        depth[node] = level
+       |        # A node belongs to whichever parent reaches it first, so a
+       |        # cycle or a shared child is never laid out twice.
+       |        kids = [kid for kid in children[node] if kid not in placed]
+       |        placed.update(kids)
+       |        claimed[node] = kids
+       |        stack.append((node, level, True))
+       |        for kid in reversed(kids):
+       |            stack.append((kid, level + 1, False))
+       |
+       |for label in labels:
+       |    if label not in placed and label not in has_parent:
+       |        grow(label)
+       |# Whatever is left sits in a cycle that no root can reach.
+       |for label in labels:
+       |    if label not in placed:
+       |        grow(label)
+       |# The y-axis is inverted here so the tree grows top-down.
+       |return labels, [(column[label], -depth[label]) for label in labels]""",
+      indent
+    )
+}
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/waterfallChart/WaterfallChartOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/waterfallChart/WaterfallChartOpDesc.scala
index 2ed883ff3b..c2e6921dec 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/waterfallChart/WaterfallChartOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/waterfallChart/WaterfallChartOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.waterfallChart
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import 
org.apache.texera.amber.pybuilder.PythonTemplateBuilder.PythonTemplateBuilderStringContext
@@ -118,14 +119,10 @@ class WaterfallChartOpDesc extends 
PythonVisualizationOpDesc with PlotlyStandalo
   }
 
   override def generateStandaloneCode(): String = {
-    s"""def render_error(error_msg) -> str:
-       |    return '''<h1>Waterfall chart is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("Waterfall chart is not available.", typed = true)}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("input table is empty."))
+       |${standaloneErrorPage("input table is empty.")}
        |else:
        |    table = in1df
        |    x_values = list(table[${pyStringLiteral(xColumn)}])
@@ -143,9 +140,7 @@ class WaterfallChartOpDesc extends 
PythonVisualizationOpDesc with PlotlyStandalo
        |    ))
        |
        |    fig.update_layout(showlegend=True, waterfallgap=0.3, 
xaxis_type="category")
-       |    fig.write_json(outputJson)
-       |    fig.write_html(outputHtml)
-       |    print("Waterfall chart saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Waterfall chart", indent = 4)}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/windRoseChart/WindRoseChartOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/windRoseChart/WindRoseChartOpDesc.scala
index dcfcead4b8..f7ed97ef2d 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/windRoseChart/WindRoseChartOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/windRoseChart/WindRoseChartOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.windRoseChart
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
 import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, 
JsonSchemaTitle}
 import org.apache.texera.amber.core.workflow.OutputPort.OutputMode
@@ -137,17 +138,12 @@ class WindRoseChartOpDesc extends 
PythonVisualizationOpDesc with PlotlyStandalon
       if (colorColumn != null && colorColumn.nonEmpty) s"""
        |            color=${pyStringLiteral(colorColumn)},"""
       else ""
-    s"""def render_error(error_msg) -> str:
-       |    return '''<h1>Wind Rose chart is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("Wind Rose chart is not available.", typed = true)}
        |
        |if in1df.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("input table is empty."))
+       |${standaloneErrorPage("input table is empty.")}
        |elif in1df[$rLit].dtype.kind not in ["i", "u", "f"]:
-       |    with open(outputHtml, "w", encoding="utf-8") as output:
-       |        output.write(render_error("Radial column must be numeric (int, 
float, or double)."))
+       |${standaloneErrorPage("Radial column must be numeric (int, float, or 
double).")}
        |else:
        |    table = in1df
        |    fig = px.bar_polar(
@@ -156,9 +152,7 @@ class WindRoseChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandalon
        |        theta=${pyStringLiteral(thetaColumn)},$colorArg
        |        color_discrete_sequence=px.colors.sequential.Plasma_r
        |    )
-       |    fig.write_json(outputJson)
-       |    fig.write_html(outputHtml)
-       |    print("Wind rose chart saved to " + outputHtml)""".stripMargin
+       |${standaloneFigure("Wind rose chart", indent = 4)}""".stripMargin
   }
 
 }
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/wordCloud/WordCloudOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/wordCloud/WordCloudOpDesc.scala
index f43a9dcda2..7ff9c39280 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/wordCloud/WordCloudOpDesc.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/wordCloud/WordCloudOpDesc.scala
@@ -19,6 +19,7 @@
 
 package org.apache.texera.amber.operator.visualization.wordCloud
 
+import org.apache.texera.amber.operator.visualization.StandaloneChartCode._
 import com.fasterxml.jackson.annotation.JsonProperty
 import com.kjetland.jackson.jsonSchema.annotations.{
   JsonSchemaInject,
@@ -138,24 +139,22 @@ class WordCloudOpDesc extends PythonVisualizationOpDesc {
   // the runtime path explains itself.
   override def generateStandaloneCode(): String = {
     val textLit = pyStringLiteral(textColumn)
-    s"""def render_error(error_msg):
-       |    return '''<h1>Wordcloud is not available.</h1>
-       |                  <p>Reason is: {} </p>
-       |               '''.format(error_msg)
+    s"""${standaloneError("Wordcloud is not available.")}
        |
        |table = in1df
        |if table.empty:
-       |    with open(outputHtml, "w", encoding="utf-8") as f:
-       |        f.write(render_error("input table is empty."))
+       |${standaloneErrorPage("input table is empty.", handle = "f")}
        |elif not (pd.api.types.is_object_dtype(table[$textLit]) or 
pd.api.types.is_string_dtype(table[$textLit])):
-       |    with open(outputHtml, "w", encoding="utf-8") as f:
-       |        f.write(render_error("$NotTextMessage"))
+       |${standaloneErrorPage(NotTextMessage, handle = "f")}
        |else:
        |    table = table.dropna(subset=[$textLit])
        |    table = table[table[$textLit].str.contains(r'\\w', regex=True)]
        |    if table.empty:
-       |        with open(outputHtml, "w", encoding="utf-8") as f:
-       |            f.write(render_error("text column does not contain words 
or contains only nulls."))
+       |${standaloneErrorPage(
+      "text column does not contain words or contains only nulls.",
+      indent = 8,
+      handle = "f"
+    )}
        |    else:
        |        text = ' '.join(table[$textLit])
        |        from wordcloud import WordCloud, STOPWORDS

Reply via email to