> ## Documentation Index
> Fetch the complete documentation index at: https://resources.latex-cloud-studio.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Using LaTeX Templates Effectively

> Master LaTeX templates for efficient document creation. Learn to find, customize, create, and share templates for various document types.

export const RenderedOutput = ({title = "Rendered output", ctaHref, ctaLabel = "Open LaTeX Cloud Studio", children}) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const trackEditorCta = () => {
    const target = new URL(ctaHref, window.location.href);
    globalThis.posthog?.capture?.("docs_app_cta_clicked", {
      source_page: window.location.pathname,
      source_section: "rendered_output",
      cta_variant: "first_compiled_example",
      target_url: target.toString(),
      target_utm_source: target.searchParams.get("utm_source"),
      target_utm_medium: target.searchParams.get("utm_medium"),
      target_utm_campaign: target.searchParams.get("utm_campaign"),
      target_utm_content: target.searchParams.get("utm_content")
    }, {
      transport: "sendBeacon",
      send_instantly: true
    });
  };
  return <details className="rendered-output" onToggle={event => setIsExpanded(event.currentTarget.open)}>
      <summary className="rendered-output__summary">
        <span className="rendered-output__title">{title}</span>
        <span className="rendered-output__hint" aria-hidden="true">View compiled result</span>
      </summary>
      {isExpanded && <div className="rendered-output__content">
          {children}
          {ctaHref && <aside className="rendered-output__cta" aria-label="Continue in the LaTeX editor">
              <span>
                <strong>Ready to use this syntax?</strong>
                Continue in the browser editor when you want to adapt the example in a real project.
              </span>
              <a href={ctaHref} onClick={trackEditorCta}>{ctaLabel}<span aria-hidden="true"> →</span></a>
            </aside>}
        </div>}
    </details>;
};

export const LatexSource = ({filename, source}) => {
  const [copyStatus, setCopyStatus] = useState("Copy");
  const copySource = async () => {
    try {
      await navigator.clipboard.writeText(source);
      setCopyStatus("Copied");
    } catch {
      setCopyStatus("Select and copy");
    }
  };
  return <figure className="latex-source">
      <figcaption className="latex-source__header">
        <span className="latex-source__filename">{filename}</span>
        <button type="button" className="latex-source__copy" onClick={copySource} aria-live="polite">
          {copyStatus}
        </button>
      </figcaption>
      <pre className="latex-source__pre" aria-label={`LaTeX source: ${filename}`} tabIndex="0">
        <code className="language-latex">{source}</code>
      </pre>
    </figure>;
};

export const LatexPreview = ({src, alt, caption, width, height}) => {
  const minZoom = 1;
  const maxZoom = 3;
  const zoomStep = 0.5;
  const measureSvgContent = async (assetSrc, pageWidth, pageHeight) => {
    const cacheKey = "__latexCloudSvgContentBoxCache";
    const contentBoxCache = globalThis[cacheKey] ?? new Map();
    globalThis[cacheKey] = contentBoxCache;
    if (contentBoxCache.has(assetSrc)) return contentBoxCache.get(assetSrc);
    const measurement = (async () => {
      const assetUrl = new URL(assetSrc, window.location.href);
      if (assetUrl.origin !== window.location.origin) {
        throw new Error("Rendered output must use a same-origin SVG asset.");
      }
      const response = await fetch(assetUrl, {
        credentials: "same-origin"
      });
      if (!response.ok) throw new Error(`Rendered output request failed with ${response.status}.`);
      const source = await response.text();
      const documentNode = new DOMParser().parseFromString(source, "image/svg+xml");
      if (documentNode.querySelector("parsererror")) throw new Error("Rendered output is not valid SVG.");
      const sourceSvg = documentNode.documentElement;
      sourceSvg.querySelectorAll("script, foreignObject").forEach(node => node.remove());
      [sourceSvg, ...sourceSvg.querySelectorAll("*")].forEach(node => {
        [...node.attributes].forEach(attribute => {
          if ((/^on/i).test(attribute.name)) node.removeAttribute(attribute.name);
          if ((attribute.name === "href" || attribute.name === "xlink:href") && !attribute.value.startsWith("#")) {
            node.removeAttribute(attribute.name);
          }
        });
      });
      const measurementHost = document.createElement("div");
      measurementHost.className = "latex-preview__measurement-host";
      const measuredSvg = document.importNode(sourceSvg, true);
      measuredSvg.setAttribute("aria-hidden", "true");
      measurementHost.appendChild(measuredSvg);
      document.body.appendChild(measurementHost);
      try {
        const measuredElements = [...measuredSvg.children].filter(node => !["defs", "desc", "metadata", "style", "title"].includes(node.tagName.toLowerCase()));
        const elementBounds = measuredElements.map(node => node.getBBox()).filter(box => [box.x, box.y, box.width, box.height].every(Number.isFinite) && box.width > 0 && box.height > 0);
        if (elementBounds.length === 0) {
          throw new Error("Rendered output has no measurable visible content.");
        }
        const sortedBounds = [...elementBounds].sort((left, right) => left.y - right.y);
        const clusterGap = pageHeight * 0.045;
        const clusters = [];
        sortedBounds.forEach(box => {
          const current = clusters[clusters.length - 1];
          if (!current || box.y - current.bottom > clusterGap) {
            clusters.push({
              boxes: [box],
              bottom: box.y + box.height
            });
            return;
          }
          current.boxes.push(box);
          current.bottom = Math.max(current.bottom, box.y + box.height);
        });
        const contentClusters = clusters.filter(cluster => {
          const clusterBox = cluster.boxes.reduce((combined, box) => {
            const right = Math.max(combined.x + combined.width, box.x + box.width);
            const bottom = Math.max(combined.y + combined.height, box.y + box.height);
            const x = Math.min(combined.x, box.x);
            const y = Math.min(combined.y, box.y);
            return {
              x,
              y,
              width: right - x,
              height: bottom - y
            };
          });
          const centerY = clusterBox.y + clusterBox.height / 2;
          const isMarginFurniture = cluster.boxes.length <= 2 && clusterBox.width < pageWidth * 0.2 && clusterBox.height < pageHeight * 0.04 && (centerY < pageHeight * 0.08 || centerY > pageHeight * 0.8);
          return !isMarginFurniture;
        });
        const visibleBounds = (contentClusters.length > 0 ? contentClusters : clusters).flatMap(cluster => cluster.boxes);
        const bounds = visibleBounds.reduce((combined, box) => {
          const right = Math.max(combined.x + combined.width, box.x + box.width);
          const bottom = Math.max(combined.y + combined.height, box.y + box.height);
          const x = Math.min(combined.x, box.x);
          const y = Math.min(combined.y, box.y);
          return {
            x,
            y,
            width: right - x,
            height: bottom - y
          };
        });
        const clampValue = (value, minimum, maximum) => Math.min(maximum, Math.max(minimum, value));
        const padding = Math.max(8, Math.min(pageWidth, pageHeight) * 0.025);
        const x = clampValue(bounds.x - padding, 0, pageWidth);
        const y = clampValue(bounds.y - padding, 0, pageHeight);
        const right = clampValue(bounds.x + bounds.width + padding, 0, pageWidth);
        const bottom = clampValue(bounds.y + bounds.height + padding, 0, pageHeight);
        return {
          x,
          y,
          width: right - x,
          height: bottom - y
        };
      } finally {
        measurementHost.remove();
      }
    })();
    contentBoxCache.set(assetSrc, measurement);
    measurement.catch(() => contentBoxCache.delete(assetSrc));
    return measurement;
  };
  const renderPreviewAsset = ({contentBox: assetContentBox, loading}) => {
    if (!assetContentBox) {
      return <img className="latex-preview__asset" src={src} alt={alt} width={width} height={height} loading={loading} draggable="false" />;
    }
    return <svg className="latex-preview__asset" viewBox={`${assetContentBox.x} ${assetContentBox.y} ${assetContentBox.width} ${assetContentBox.height}`} preserveAspectRatio="xMidYMid meet" role="img" aria-label={alt}>
        <image href={src} x="0" y="0" width={width} height={height} />
      </svg>;
  };
  const [isOpen, setIsOpen] = useState(false);
  const [frameMode, setFrameMode] = useState("content");
  const [viewMode, setViewMode] = useState("fit");
  const [zoom, setZoom] = useState(minZoom);
  const [contentBox, setContentBox] = useState(null);
  const [measurementStatus, setMeasurementStatus] = useState("loading");
  const dialogRef = useRef(null);
  const closeButtonRef = useRef(null);
  const viewportRef = useRef(null);
  const previousFocusRef = useRef(null);
  const dragRef = useRef(null);
  useEffect(() => {
    let isCurrent = true;
    setMeasurementStatus("loading");
    measureSvgContent(src, width, height).then(box => {
      if (!isCurrent) return;
      setContentBox(box);
      setMeasurementStatus("ready");
    }).catch(() => {
      if (!isCurrent) return;
      setContentBox(null);
      setFrameMode("page");
      setMeasurementStatus("error");
    });
    return () => {
      isCurrent = false;
    };
  }, [height, src, width]);
  const closeViewer = useCallback(() => {
    setIsOpen(false);
  }, []);
  const openViewer = () => {
    previousFocusRef.current = document.activeElement;
    setFrameMode(contentBox ? "content" : "page");
    setViewMode("fit");
    setZoom(minZoom);
    setIsOpen(true);
  };
  const applyZoom = useCallback(nextZoom => {
    const boundedZoom = Math.min(maxZoom, Math.max(minZoom, nextZoom));
    setViewMode("custom");
    setZoom(boundedZoom);
  }, []);
  const zoomIn = useCallback(() => {
    applyZoom(viewMode === "fit" ? minZoom + zoomStep : zoom + zoomStep);
  }, [applyZoom, viewMode, zoom]);
  const zoomOut = useCallback(() => {
    applyZoom(viewMode === "fit" ? minZoom : zoom - zoomStep);
  }, [applyZoom, viewMode, zoom]);
  useEffect(() => {
    if (!isOpen) return undefined;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    closeButtonRef.current?.focus();
    return () => {
      document.body.style.overflow = previousOverflow;
      previousFocusRef.current?.focus?.();
    };
  }, [isOpen]);
  useEffect(() => {
    if (!isOpen) return undefined;
    const handleKeyDown = event => {
      if (event.key === "Escape") {
        event.preventDefault();
        closeViewer();
        return;
      }
      if ((event.key === "+" || event.key === "=") && !event.metaKey && !event.ctrlKey) {
        event.preventDefault();
        zoomIn();
        return;
      }
      if (event.key === "-" && !event.metaKey && !event.ctrlKey) {
        event.preventDefault();
        zoomOut();
        return;
      }
      if (event.key !== "Tab" || !dialogRef.current) return;
      const focusable = [...dialogRef.current.querySelectorAll('button:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])')];
      if (focusable.length === 0) return;
      const first = focusable[0];
      const last = focusable[focusable.length - 1];
      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [closeViewer, isOpen, zoomIn, zoomOut]);
  const startDrag = event => {
    if (event.button !== 0 || !viewportRef.current) return;
    const viewport = viewportRef.current;
    dragRef.current = {
      pointerId: event.pointerId,
      x: event.clientX,
      y: event.clientY,
      scrollLeft: viewport.scrollLeft,
      scrollTop: viewport.scrollTop
    };
    viewport.setPointerCapture(event.pointerId);
    viewport.dataset.dragging = "true";
  };
  const continueDrag = event => {
    const drag = dragRef.current;
    const viewport = viewportRef.current;
    if (!drag || !viewport || drag.pointerId !== event.pointerId) return;
    viewport.scrollLeft = drag.scrollLeft - (event.clientX - drag.x);
    viewport.scrollTop = drag.scrollTop - (event.clientY - drag.y);
  };
  const stopDrag = event => {
    const viewport = viewportRef.current;
    if (viewport?.hasPointerCapture(event.pointerId)) viewport.releasePointerCapture(event.pointerId);
    if (viewport) delete viewport.dataset.dragging;
    dragRef.current = null;
  };
  const activeContentBox = frameMode === "content" ? contentBox : null;
  const activeWidth = activeContentBox?.width ?? width;
  const activeHeight = activeContentBox?.height ?? height;
  const activeRatio = activeWidth / activeHeight;
  const inlineContentBox = measurementStatus === "ready" ? contentBox : null;
  const inlineWidth = inlineContentBox?.width ?? width;
  const inlineHeight = inlineContentBox?.height ?? height;
  const inlineGeometry = {
    aspectRatio: `${inlineWidth} / ${inlineHeight}`,
    maxWidth: `${30 * inlineWidth / inlineHeight}rem`
  };
  const imageStyle = viewMode === "fit" ? {
    aspectRatio: `${activeWidth} / ${activeHeight}`,
    width: "100%",
    maxWidth: `${Math.max(16, activeRatio * 78)}dvh`
  } : {
    aspectRatio: `${activeWidth} / ${activeHeight}`,
    width: `${zoom * 100}%`,
    maxWidth: "none"
  };
  const zoomLabel = viewMode === "fit" ? frameMode === "content" ? "Fit content" : "Full page" : `${Math.round(zoom * 100)}%`;
  return <figure className="latex-preview">
      <button type="button" className="latex-preview__trigger" onClick={openViewer} aria-haspopup="dialog" aria-label={`Open zoomable preview: ${alt}`}>
        <span className="latex-preview__page" style={inlineGeometry}>
          {measurementStatus === "loading" ? <span className="latex-preview__loading" role="status">Preparing compiled output…</span> : renderPreviewAsset({
    src,
    alt,
    width,
    height,
    contentBox: inlineContentBox,
    loading: "lazy"
  })}
        </span>
        <span className="latex-preview__trigger-label" aria-hidden="true">
          <span className="latex-preview__trigger-icon">⌕</span>
          Open viewer
        </span>
      </button>
      <figcaption className="latex-preview__caption">
        <span>
          {caption}
          {measurementStatus === "error" && <span className="latex-preview__status" role="status"> Content fit is unavailable; the complete vector page is shown.</span>}
        </span>
        <a href={src} target="_blank" rel="noreferrer" className="latex-preview__source-link">Open SVG</a>
      </figcaption>

      {isOpen && <div className="latex-preview__backdrop" onMouseDown={event => {
    if (event.target === event.currentTarget) closeViewer();
  }}>
          <section ref={dialogRef} className="latex-preview__dialog" role="dialog" aria-modal="true" aria-label={`Rendered LaTeX viewer: ${alt}`}>
            <header className="latex-preview__toolbar">
              <div className="latex-preview__identity">
                <span className="latex-preview__eyebrow">Compiled LaTeX</span>
                <span className="latex-preview__filename">{alt}</span>
              </div>
              <div className="latex-preview__controls" aria-label="Preview controls">
                <button type="button" className={frameMode === "content" && viewMode === "fit" ? "is-active" : undefined} disabled={!contentBox} onClick={() => {
    setFrameMode("content");
    setViewMode("fit");
    setZoom(minZoom);
  }}>
                  Fit content
                </button>
                <button type="button" className={frameMode === "page" && viewMode === "fit" ? "is-active" : undefined} onClick={() => {
    setFrameMode("page");
    setViewMode("fit");
    setZoom(minZoom);
  }}>
                  Full page
                </button>
                <span className="latex-preview__zoom-group">
                  <button type="button" onClick={zoomOut} disabled={viewMode === "fit" || zoom <= minZoom} aria-label="Zoom out">−</button>
                  <output aria-live="polite" aria-label="Current zoom">{zoomLabel}</output>
                  <button type="button" onClick={zoomIn} disabled={viewMode !== "fit" && zoom >= maxZoom} aria-label="Zoom in">+</button>
                </span>
                <a href={src} target="_blank" rel="noreferrer">Open SVG</a>
                <button ref={closeButtonRef} type="button" className="latex-preview__close" onClick={closeViewer} aria-label="Close rendered LaTeX viewer">
                  Close
                </button>
              </div>
            </header>
            <div ref={viewportRef} className="latex-preview__viewport" data-view-mode={viewMode} onPointerDown={startDrag} onPointerMove={continueDrag} onPointerUp={stopDrag} onPointerCancel={stopDrag}>
              <span className="latex-preview__dialog-page" style={imageStyle}>
                {renderPreviewAsset({
    src,
    alt,
    width,
    height,
    contentBox: activeContentBox
  })}
              </span>
            </div>
            <footer className="latex-preview__viewer-note">
              Compiler-generated vector output · Use +/− to zoom · Drag to pan · Esc to close
            </footer>
          </section>
        </div>}
    </figure>;
};

Save time and ensure consistency by mastering LaTeX templates. This guide covers finding quality templates, customization techniques, creating your own templates, and sharing them with others.

<Info>
  **Prerequisites**: Basic LaTeX knowledge\
  **Time to complete**: 25-30 minutes\
  **Difficulty**: Intermediate\
  **What you'll learn**: Template sources, customization, creation, package development, and distribution
</Info>

## Understanding LaTeX Templates

### What Makes a Good Template?

<CardGroup cols={2}>
  <Card title="Well-Structured" icon="sitemap">
    Clear organization with logical sections and includes
  </Card>

  <Card title="Documented" icon="book">
    Comments explaining usage and customization options
  </Card>

  <Card title="Flexible" icon="shuffle">
    Easy to adapt for different use cases
  </Card>

  <Card title="Complete" icon="check-double">
    Includes all necessary packages and settings
  </Card>
</CardGroup>

### Template Components

```
template/
├── main.tex              # Main template file
├── template.cls          # Custom class (optional)
├── template.sty          # Style package (optional)
├── README.md            # Documentation
├── example/             # Example usage
│   ├── example.tex
│   ├── example.pdf
│   └── figures/
├── lib/                 # Supporting files
│   ├── commands.tex     # Custom commands
│   ├── environments.tex # Custom environments
│   └── packages.tex     # Package imports
└── assets/              # Logos, images
```

## Finding Templates

### Quality Template Sources

<Tabs>
  <Tab title="LaTeX Cloud Studio">
    Built-in template gallery with:

    * Academic papers
    * Presentations
    * CVs and resumes
    * Books and reports
    * Posters
    * Letters
  </Tab>

  <Tab title="CTAN">
    **Comprehensive TeX Archive Network**

    * Official packages
    * Document classes
    * Quality assured
    * Well documented

    Browse: [ctan.org](https://ctan.org)
  </Tab>

  <Tab title="University Templates">
    Many universities provide:

    * Thesis templates
    * Dissertation formats
    * Department styles
    * Branding guidelines
  </Tab>

  <Tab title="Community">
    **GitHub/GitLab**

    * Open source templates
    * Version controlled
    * Community maintained
    * Issue tracking
  </Tab>
</Tabs>

### Evaluating Templates

<CodeGroup>
  ```latex template-evaluation.tex theme={null}
  % Check these aspects before using a template

  % 1. License - Can you use/modify it?
  % Look for LICENSE file or header comments

  % 2. Dependencies - What packages are required?
  \usepackage{required-package} % Is this available?

  % 3. Compatibility - Does it work with your setup?
  \documentclass{template-class} % Does this compile?

  % 4. Customization - How flexible is it?
  \settemplateoption{key}{value} % Are options documented?

  % 5. Maintenance - Is it actively maintained?
  % Check last update date and issue tracker
  ```

  ```bash template-testing.sh theme={null}
  #!/bin/bash
  # Test template before adopting

  # 1. Clone/download template
  git clone https://github.com/user/latex-template
  cd latex-template

  # 2. Check structure
  find . -name "*.tex" -o -name "*.cls" -o -name "*.sty" | head -20

  # 3. Test compilation
  pdflatex example/example.tex
  if [ $? -eq 0 ]; then
      echo "Template compiles successfully"
  else
      echo "Compilation failed - check dependencies"
  fi

  # 4. Review output
  open example/example.pdf  # macOS
  # xdg-open example/example.pdf  # Linux
  ```
</CodeGroup>

<RenderedOutput title="Expected effect">
  <Info>
    This code group documents a multi-step workflow across LaTeX and another file or command language. The blocks work together in a project, so there is no single standalone LaTeX page that would honestly represent the whole group.
  </Info>
</RenderedOutput>

## Customizing Templates

### Basic Customization

<LatexSource filename="customize-basics.tex" source={"% Most templates provide customization options\n\n% 1. Document metadata\n\\title{Your Document Title}\n\\author{Your Name}\n\\date{\\today}\n\\institution{Your University}\n\n% 2. Style options\n\\documentclass[\n    12pt,           % Font size\n    letterpaper,    % Paper size\n    twoside,        % Two-sided printing\n    draft           % Draft mode\n]{template-class}\n\n% 3. Color schemes\n\\definecolor{primary}{RGB}{0, 51, 102}\n\\definecolor{secondary}{RGB}{255, 128, 0}\n\\setbeamercolor{title}{fg=primary}\n\n% 4. Fonts\n\\usepackage{libertine}  % Change main font\n\\usepackage[libertine]{newtxmath}  % Matching math font\n\n% 5. Layout adjustments\n\\geometry{\n    margin=1in,\n    headheight=15pt\n}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

<LatexSource filename="advanced-customization.tex" source={"% Deeper customization techniques\n\n% Override template commands\n\\let\\oldtitle\\title\n\\renewcommand{\\title}[1]{%\n    \\oldtitle{\\MakeUppercase{#1}}%\n}\n\n% Modify environments\n\\let\\oldabstract\\abstract\n\\let\\endoldabstract\\endabstract\n\\renewenvironment{abstract}{%\n    \\begin{center}\n    \\textbf{ABSTRACT}\n    \\end{center}\n    \\oldabstract\n}{%\n    \\endoldabstract\n}\n\n% Hook into template internals\n\\makeatletter\n\\renewcommand{\\@maketitle}{%\n    % Custom title page layout\n    \\begin{center}\n        {\\LARGE \\@title \\par}\n        \\vskip 2em\n        {\\large \\@author \\par}\n        \\vskip 1em\n        {\\@date \\par}\n    \\end{center}\n}\n\\makeatother"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

### Package-based Templates

<LatexSource filename="using-class-options.tex" source={"% Article class with custom options\n\\documentclass[journal]{IEEEtran}\n% Options: conference, journal, technote, peerreview\n\n% Beamer with themes\n\\documentclass{beamer}\n\\usetheme{Madrid}\n\\usecolortheme{beaver}\n\\usefonttheme{professionalfonts}\n\n% Memoir class flexibility\n\\documentclass[\n    11pt,\n    oneside,\n    article,  % Article mode\n    extrafontsizes\n]{memoir}\n\n% KOMA-Script customization\n\\documentclass[\n    paper=a4,\n    fontsize=11pt,\n    DIV=12,  % Type area calculation\n    BCOR=10mm,  % Binding correction\n    parskip=half  % Paragraph spacing\n]{scrartcl}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This is document setup or preamble code. It changes the behavior of a containing document but does not produce an honest standalone page by itself.
  </Info>
</RenderedOutput>

<LatexSource filename="template-packages.tex" source={"% Common template packages\n\n% Academic papers\n\\usepackage{acmart}         % ACM articles\n\\usepackage{IEEEtran}       % IEEE transactions\n\\usepackage{elsarticle}     % Elsevier journals\n\\usepackage{revtex4-2}      % Physics journals\n\n% Presentations\n\\usepackage{beamer}         % Presentations\n\\usepackage{beamerposter}   % Posters\n\n% Books/Reports\n\\usepackage{memoir}         % Flexible book class\n\\usepackage{scrbook}        % KOMA-Script book\n\\usepackage{tufte-latex}    % Tufte-style layouts\n\n% CVs/Resumes\n\\usepackage{moderncv}       % Modern CV\n\\usepackage{europecv}       % European CV format\n\\usepackage{curve}          % Another CV class"} />

<RenderedOutput title="Expected effect">
  <Info>
    This is setup or structural LaTeX code. It changes available commands or document behavior, but it does not produce meaningful standalone page content by itself.
  </Info>
</RenderedOutput>

## Creating Your Own Templates

### Template Structure

<LatexSource filename="basic-template.tex" source={"% my-template.tex - Basic article template\n\\documentclass[11pt, a4paper]{article}\n\n% ====================================\n% PACKAGES\n% ====================================\n\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\\usepackage{lmodern}\n\\usepackage[margin=1in]{geometry}\n\\usepackage{graphicx}\n\\usepackage{hyperref}\n\n% ====================================\n% CUSTOM COMMANDS\n% ====================================\n\\newcommand{\\projectname}[1]{\\def\\@projectname{#1}}\n\\newcommand{\\supervisor}[1]{\\def\\@supervisor{#1}}\n\n% ====================================\n% DOCUMENT SETTINGS\n% ====================================\n\\hypersetup{\n    colorlinks=true,\n    linkcolor=blue,\n    citecolor=green,\n    urlcolor=red\n}\n\n% ====================================\n% TITLE PAGE REDEFINITION\n% ====================================\n\\makeatletter\n\\renewcommand{\\maketitle}{%\n    \\begin{titlepage}\n        \\centering\n        \\vspace*{2cm}\n\n        {\\Huge\\bfseries \\@title \\par}\n        \\vspace{1cm}\n\n        {\\Large Project: \\@projectname \\par}\n        \\vspace{2cm}\n\n        {\\Large\\itshape \\@author \\par}\n        \\vspace{0.5cm}\n\n        {\\large Supervisor: \\@supervisor \\par}\n        \\vfill\n\n        {\\large \\@date \\par}\n    \\end{titlepage}\n}\n\\makeatother\n\n% ====================================\n% BEGIN DOCUMENT\n% ====================================\n\\begin{document}\n\n% User fills these\n\\title{Your Title Here}\n\\author{Your Name}\n\\projectname{Project Name}\n\\supervisor{Dr. Supervisor}\n\\date{\\today}\n\n\\maketitle\n\n\\begin{abstract}\nYour abstract here...\n\\end{abstract}\n\n\\tableofcontents\n\\newpage\n\n\\section{Introduction}\nStart writing here...\n\n\\end{document}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

<LatexSource filename="modular-template.tex" source={"% main-template.tex - Modular approach\n\\documentclass{article}\n\n% Load template components\n\\input{template-config/packages}\n\\input{template-config/settings}\n\\input{template-config/commands}\n\\input{template-config/environments}\n\n\\begin{document}\n\n\\input{template-parts/titlepage}\n\\input{template-parts/abstract}\n\n\\tableofcontents\n\\listoffigures\n\\listoftables\n\n% User content sections\n\\input{sections/introduction}\n\\input{sections/methodology}\n\\input{sections/results}\n\\input{sections/conclusion}\n\n\\bibliographystyle{plain}\n\\bibliography{references}\n\n\\appendix\n\\input{appendices/appendix-a}\n\n\\end{document}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

### Custom Document Class

<LatexSource filename="myclass.cls" source={"% myclass.cls - Custom document class\n\\NeedsTeXFormat{LaTeX2e}\n\\ProvidesClass{myclass}[2024/01/01 My Custom Class]\n\n% Base class\n\\LoadClass[11pt, a4paper]{article}\n\n% Required packages\n\\RequirePackage[margin=1in]{geometry}\n\\RequirePackage{graphicx}\n\\RequirePackage{hyperref}\n\\RequirePackage{fancyhdr}\n\n% Class options\n\\DeclareOption{draft}{\n    \\PassOptionsToClass{draft}{article}\n    \\AtEndOfClass{\\usepackage[disable]{todonotes}}\n}\n\\DeclareOption{final}{\n    \\PassOptionsToClass{final}{article}\n}\n\\ProcessOptions\\relax\n\n% Custom commands\n\\newcommand{\\institution}[1]{\\gdef\\@institution{#1}}\n\\newcommand{\\department}[1]{\\gdef\\@department{#1}}\n\n% Headers and footers\n\\pagestyle{fancy}\n\\fancyhf{}\n\\fancyhead[L]{\\@title}\n\\fancyhead[R]{\\@author}\n\\fancyfoot[C]{\\thepage}\n\n% Title page\n\\renewcommand{\\maketitle}{%\n    \\begin{titlepage}\n        \\centering\n        \\vspace*{1cm}\n\n        \\includegraphics[width=0.3\\textwidth]{logo}\\par\n        \\vspace{1cm}\n\n        {\\scshape\\LARGE \\@institution \\par}\n        \\vspace{0.5cm}\n        {\\scshape\\Large \\@department \\par}\n        \\vspace{2cm}\n\n        {\\huge\\bfseries \\@title \\par}\n        \\vspace{2cm}\n\n        {\\Large\\itshape \\@author \\par}\n        \\vfill\n\n        {\\large \\@date \\par}\n    \\end{titlepage}\n}\n\n% Theorem environments\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{lemma}[theorem]{Lemma}\n\\newtheorem{proposition}[theorem]{Proposition}\n\n\\endinput"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

<LatexSource filename="myclass-usage.tex" source={"% Using the custom class\n\\documentclass[draft]{myclass}\n\n\\title{Research Paper}\n\\author{Jane Doe}\n\\institution{University Name}\n\\department{Computer Science}\n\\date{\\today}\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\nThis paper presents...\n\\end{abstract}\n\n\\section{Introduction}\nOur custom class provides...\n\n\\begin{theorem}\nLet $X$ be a...\n\\end{theorem}\n\n\\end{document}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

### Style Package Creation

<LatexSource filename="mystyle.sty" source={"% mystyle.sty - Reusable style package\n\\NeedsTeXFormat{LaTeX2e}\n\\ProvidesPackage{mystyle}[2024/01/01 My Style Package]\n\n% Package options\n\\newif\\if@colorful\n\\DeclareOption{colorful}{\\@colorfultrue}\n\\DeclareOption{plain}{\\@colorfulfalse}\n\\ProcessOptions\\relax\n\n% Dependencies\n\\RequirePackage{xcolor}\n\\RequirePackage{tikz}\n\\RequirePackage{tcolorbox}\n\n% Color definitions\n\\if@colorful\n    \\definecolor{primary}{RGB}{0, 102, 204}\n    \\definecolor{secondary}{RGB}{255, 128, 0}\n    \\definecolor{accent}{RGB}{0, 153, 0}\n\\else\n    \\definecolor{primary}{gray}{0.2}\n    \\definecolor{secondary}{gray}{0.4}\n    \\definecolor{accent}{gray}{0.6}\n\\fi\n\n% Custom box environment\n\\newtcolorbox{mybox}[2][]{\n    colback=primary!5!white,\n    colframe=primary!75!black,\n    title=#2,\n    #1\n}\n\n% Section formatting\n\\RequirePackage{titlesec}\n\\titleformat{\\section}\n    {\\normalfont\\Large\\bfseries\\color{primary}}\n    {\\thesection}{1em}{}\n\n% Custom commands\n\\newcommand{\\highlight}[1]{%\n    \\textcolor{accent}{\\textbf{#1}}%\n}\n\n\\newcommand{\\keyword}[1]{%\n    \\textcolor{secondary}{\\textit{#1}}%\n}\n\n% Custom list environment\n\\newenvironment{mylist}{%\n    \\begin{itemize}\n        \\setlength{\\itemsep}{0.5em}\n        \\renewcommand{\\labelitemi}{%\n            \\textcolor{primary}{\\textbullet}%\n        }\n}{%\n    \\end{itemize}\n}\n\n\\endinput"} />

<RenderedOutput title="Expected effect">
  <Info>
    This is document setup or preamble code. It changes the behavior of a containing document but does not produce an honest standalone page by itself.
  </Info>
</RenderedOutput>

<LatexSource filename="using-mystyle.tex" source={"% Using the custom style\n\\documentclass{article}\n\\usepackage[colorful]{mystyle}\n\n\\begin{document}\n\n\\section{Introduction}\nThis document uses our \\highlight{custom style}.\n\n\\begin{mybox}{Important Note}\nThis is a custom colored box environment.\n\\end{mybox}\n\nKey concepts:\n\\begin{mylist}\n    \\item First \\keyword{concept}\n    \\item Second \\keyword{idea}\n    \\item Third \\keyword{principle}\n\\end{mylist}\n\n\\end{document}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

## Template Distribution

### Packaging Templates

<CodeGroup>
  ````bash create-template-package.sh theme={null}
  #!/bin/bash
  # Package template for distribution

  PROJECT="my-latex-template"
  VERSION="1.0.0"

  # Create directory structure
  mkdir -p $PROJECT/{doc,examples,src}

  # Copy template files
  cp template.cls $PROJECT/src/
  cp template.sty $PROJECT/src/
  cp -r examples/* $PROJECT/examples/

  # Create documentation
  cat > $PROJECT/README.md << 'EOF'
  # My LaTeX Template

  ## Installation

  ### Method 1: Local Installation
  Place files in your LaTeX project directory.

  ### Method 2: System Installation
  ```bash
  mkdir -p ~/texmf/tex/latex/my-template
  cp src/* ~/texmf/tex/latex/my-template/
  texhash ~/texmf
  ````

  ### Method 3: Using LaTeX Cloud Studio

  Upload as custom template in your workspace.

  ## Usage

  ```latex theme={null}
  \documentclass{my-template}
  \begin{document}
  Your content here
  \end{document}
  ```

  ## Options

  * `draft` - Enable draft mode
  * `final` - Final version (default)
  * `twoside` - Two-sided printing

  ## Examples

  See the `examples/` directory for complete examples.

  ## License

  This template is released under the MIT License.
  EOF

  # Create ZIP archive

  zip -r $PROJECT-$VERSION.zip \$PROJECT/

  echo "Template package created: $PROJECT-$VERSION.zip"

  ````

  ```latex template-documentation.tex
  % template-doc.tex - User documentation
  \documentclass{ltxdoc}
  \usepackage{hyperref}

  \title{The \textsf{my-template} Package}
  \author{Your Name}
  \date{Version 1.0.0 \\ \today}

  \begin{document}
  \maketitle

  \begin{abstract}
  This package provides a customizable template for academic documents with support for multiple layouts and styles.
  \end{abstract}

  \tableofcontents

  \section{Introduction}
  The \textsf{my-template} package simplifies document creation...

  \section{Installation}
  \subsection{Requirements}
  \begin{itemize}
      \item \LaTeX{} distribution (TeX Live 2020+)
      \item Required packages: \texttt{geometry}, \texttt{graphicx}
  \end{itemize}

  \subsection{Installation Methods}
  \begin{enumerate}
      \item Local installation...
      \item System-wide installation...
  \end{enumerate}

  \section{Usage}
  \subsection{Basic Usage}
  \begin{verbatim}
  \documentclass{my-template}
  \title{Your Title}
  \author{Your Name}
  \begin{document}
  \maketitle
  Your content...
  \end{document}
  \end{verbatim}

  \subsection{Options}
  \begin{description}
      \item[\texttt{draft}] Enable draft mode
      \item[\texttt{twoside}] Two-sided layout
  \end{description}

  \section{Customization}
  \subsection{Colors}
  Define custom colors:
  \begin{verbatim}
  \definecolor{mycolor}{RGB}{100,150,200}
  \setmaincolor{mycolor}
  \end{verbatim}

  \section{Examples}
  Complete examples are provided in the \texttt{examples/} directory.

  \end{document}
  ````
</CodeGroup>

<RenderedOutput title="Expected effect">
  <Info>
    This code group documents a multi-step workflow across LaTeX and another file or command language. The blocks work together in a project, so there is no single standalone LaTeX page that would honestly represent the whole group.
  </Info>
</RenderedOutput>

### Sharing Templates

<Tabs>
  <Tab title="GitHub">
    ```yaml theme={null}
    # .github/workflows/release.yml
    name: Release Template

    on:
      push:
        tags:
          - 'v*'

    jobs:
      release:
        runs-on: ubuntu-latest
        steps:
        - uses: actions/checkout@v2
        
        - name: Build documentation
          run: |
            pdflatex template-doc.tex
            pdflatex template-doc.tex
        
        - name: Create release package
          run: |
            ./create-package.sh
        
        - name: Create Release
          uses: actions/create-release@v1
          with:
            tag_name: ${{ github.ref }}
            release_name: Release ${{ github.ref }}
            files: |
              template-*.zip
              template-doc.pdf
    ```
  </Tab>

  <Tab title="CTAN">
    ```bash theme={null}
    # Prepare for CTAN submission
    # 1. Follow CTAN guidelines
    # 2. Create proper directory structure
    # 3. Include comprehensive documentation
    # 4. Test on multiple systems
    # 5. Submit via https://ctan.org/upload
    ```
  </Tab>

  <Tab title="Institutional">
    <LatexSource filename="example.tex" source={"% Share within organization\n% 1. Internal Git repository\n% 2. Shared network drive\n% 3. Template gallery\n% 4. Documentation wiki"} />

    <RenderedOutput title="Expected effect">
      <Info>
        This is setup or structural LaTeX code. It changes available commands or document behavior, but it does not produce meaningful standalone page content by itself.
      </Info>
    </RenderedOutput>
  </Tab>
</Tabs>

## Template Best Practices

### Design Principles

<Tip>
  **Template design checklist**:

  * [ ] Clear documentation with examples
  * [ ] Sensible defaults
  * [ ] Minimal dependencies
  * [ ] Error handling
  * [ ] Backward compatibility
  * [ ] Semantic commands
  * [ ] Consistent naming
  * [ ] Modular structure
  * [ ] Version tracking
  * [ ] License included
</Tip>

### Common Mistakes

<Warning>
  **Avoid these template pitfalls**:

  1. **Hard-coded values** - Use commands/options
  2. **Absolute paths** - Always relative
  3. **Missing dependencies** - Document requirements
  4. **No examples** - Include working examples
  5. **Poor documentation** - Explain everything
  6. **Breaking changes** - Maintain compatibility
  7. **Complex setup** - Keep it simple
</Warning>

## Complete Template Example

<LatexSource filename="professional-template.cls" source={"% professional-template.cls\n\\NeedsTeXFormat{LaTeX2e}\n\\ProvidesClass{professional-template}[2024/01/01 v1.0]\n\n% Class options\n\\DeclareOption*{\\PassOptionsToClass{\\CurrentOption}{article}}\n\\ProcessOptions\\relax\n\\LoadClass{article}\n\n% Essential packages\n\\RequirePackage[utf8]{inputenc}\n\\RequirePackage[T1]{fontenc}\n\\RequirePackage{geometry}\n\\RequirePackage{fancyhdr}\n\\RequirePackage{graphicx}\n\\RequirePackage{hyperref}\n\\RequirePackage{xcolor}\n\n% Layout\n\\geometry{\n    paper=a4paper,\n    margin=1in,\n    headheight=14pt\n}\n\n% Colors\n\\definecolor{themecolor}{RGB}{0, 102, 204}\n\\definecolor{lightgray}{gray}{0.95}\n\n% Headers and footers\n\\pagestyle{fancy}\n\\fancyhf{}\n\\fancyhead[L]{\\small\\@title}\n\\fancyhead[R]{\\small\\@author}\n\\fancyfoot[C]{\\small Page \\thepage}\n\\renewcommand{\\headrulewidth}{0.4pt}\n\\renewcommand{\\footrulewidth}{0.4pt}\n\n% Custom commands\n\\newcommand{\\subtitle}[1]{\\gdef\\@subtitle{#1}}\n\\newcommand{\\institution}[1]{\\gdef\\@institution{#1}}\n\\newcommand{\\email}[1]{\\gdef\\@email{#1}}\n\n% Title page\n\\renewcommand{\\maketitle}{%\n    \\thispagestyle{empty}\n    \\begin{center}\n        \\vspace*{2cm}\n\n        {\\Huge\\bfseries\\color{themecolor} \\@title \\par}\n\n        \\ifdef{\\@subtitle}{\n            \\vspace{0.5cm}\n            {\\Large \\@subtitle \\par}\n        }{}\n\n        \\vspace{2cm}\n\n        {\\Large \\@author \\par}\n\n        \\ifdef{\\@email}{\n            \\vspace{0.3cm}\n            {\\normalsize \\href{mailto:\\@email}{\\@email} \\par}\n        }{}\n\n        \\ifdef{\\@institution}{\n            \\vspace{0.5cm}\n            {\\large \\@institution \\par}\n        }{}\n\n        \\vfill\n\n        {\\large \\@date \\par}\n    \\end{center}\n    \\newpage\n    \\setcounter{page}{1}\n}\n\n% Abstract formatting\n\\renewenvironment{abstract}{%\n    \\begin{center}\n        \\begin{minipage}{0.9\\textwidth}\n            \\rule{\\textwidth}{0.4pt}\n            \\vspace{0.2cm}\n\n            {\\large\\bfseries Abstract}\n\n            \\vspace{0.3cm}\n}{%\n            \\vspace{0.2cm}\n\n            \\rule{\\textwidth}{0.4pt}\n        \\end{minipage}\n    \\end{center}\n    \\vspace{1cm}\n}\n\n% Section formatting\n\\RequirePackage{titlesec}\n\\titleformat{\\section}\n    {\\normalfont\\Large\\bfseries\\color{themecolor}}\n    {\\thesection}{1em}{}\n\\titleformat{\\subsection}\n    {\\normalfont\\large\\bfseries}\n    {\\thesubsection}{1em}{}\n\n% Custom environments\n\\RequirePackage{tcolorbox}\n\\newtcolorbox{highlight}{\n    colback=lightgray,\n    colframe=themecolor,\n    boxrule=1pt,\n    arc=2mm,\n    left=5mm,\n    right=5mm,\n    top=3mm,\n    bottom=3mm\n}\n\n\\endinput"} />

<RenderedOutput title="Expected effect">
  <Info>
    This is document setup or preamble code. It changes the behavior of a containing document but does not produce an honest standalone page by itself.
  </Info>
</RenderedOutput>

<LatexSource filename="template-example.tex" source={"% Example using professional-template\n\\documentclass{professional-template}\n\n\\title{Professional Document Template}\n\\subtitle{A Complete Example}\n\\author{John Doe}\n\\email{john.doe&#64;example.com}\n\\institution{Example University}\n\\date{\\today}\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\nThis document demonstrates the features of our professional template, including custom title pages, formatted sections, and special environments. The template is designed for academic and professional documents.\n\\end{abstract}\n\n\\tableofcontents\n\\newpage\n\n\\section{Introduction}\nThis template provides a clean, professional layout suitable for various document types.\n\n\\begin{highlight}\nKey features include automatic formatting, custom environments, and consistent styling throughout the document.\n\\end{highlight}\n\n\\section{Usage}\nSimply use the document class and fill in your content:\n\n\\begin{verbatim}\n\\documentclass{professional-template}\n\\title{Your Title}\n\\author{Your Name}\n\\begin{document}\n\\maketitle\nYour content here...\n\\end{document}\n\\end{verbatim}\n\n\\section{Conclusion}\nThis template streamlines document creation while maintaining professional appearance.\n\n\\end{document}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

## Next Steps

Continue improving your LaTeX workflow:

<CardGroup cols={2}>
  <Card title="Fixing Errors" icon="bug" href="/learn/latex/how-to/fixing-compilation-errors">
    Debug template issues
  </Card>

  <Card title="Large Documents" icon="file-code" href="/learn/latex/how-to/large-documents">
    Templates for books/theses
  </Card>

  <Card title="Collaboration" icon="users" href="/learn/latex/how-to/collaboration-workflow">
    Share templates with teams
  </Card>

  <Card title="Research Papers" icon="microscope" href="/learn/latex/how-to/writing-research-paper">
    Academic paper templates
  </Card>
</CardGroup>

***

<Info>
  **Pro tip**: Start with existing templates and gradually customize them to your needs. Once you have a working template you like, version control it and document any customizations for future reference.
</Info>
